Mental model: Think of a set as a bag of marbles where no two marbles are identical. If you drop in another red marble, the bag still holds just one. You cannot ask for "the second item" because there is no order; you can only check if a specific color exists.
Why this matters: Real programs constantly need to track unique entities without duplicates: the set of logged-in user IDs, distinct error codes in a log file, or available seats on a flight. Sets handle these scenarios faster and cleaner than lists.
Creating Unique Collections
# Using curly braces
scores = {'A', 'B', 'C'}
print(scores)
# Converting a list with duplicates
raw_temps = [20, 21, 21, 22]
distinct_temps = set(raw_temps)
print(distinct_temps)The first line creates a set directly. The second converts a list, stripping out the repeated
21. Notice that you cannot index into a set like scores[0] because items have no fixed position.Adding and Removing Items
# Add new unique items
allowed_users = {'alice', 'bob'}
allowed_users.add('charlie')
print(allowed_users)
# Safe removal: discard does nothing if missing
allowed_users.discard('dave') # no error raised
print(allowed_users)add() inserts a new item or ignores it if already present. discard() removes an item if it exists but stays silent otherwise, making it ideal for cleanup tasks where you are not sure what is currently in the set.Set Operations
# Union: all unique items from both
python_devs = {'alice', 'bob'}
java_devs = {'bob', 'charlie'}
all_developers = python_devs | java_devs
print(all_developers)
# Intersection: common to both
polyglots = python_devs & java_devs
print(polyglots)| merges two sets into one unique collection. & finds the overlap, useful for identifying who can speak both languages.python_devs = {'alice', 'bob'}
java_devs = {'bob', 'charlie'}
# Difference: items in first but not second
python_only = python_devs - java_devs
print(python_only)- subtracts the second set from the first. This is perfect for finding who knows Python but not Java.