Sets
Overview
A set is a collection of unique items with no order. It answers questions like “have I seen this before?”, “which items are in both lists?” and “what are all the different values?” — quickly and in very little code.
Creating sets
colours = {"red", "green", "blue"}
numbers = set([3, 1, 3, 2, 1]) # {1, 2, 3} — duplicates disappear
letters = set("hello") # {'h', 'e', 'l', 'o'}
empty = set() # NOT {} — that's an empty dictionaryTwo key properties:
- No duplicates. Adding an item that’s already there does nothing.
{1, 2, 2, 3} == {1, 2, 3}. - No order. There’s no first item and no indexing (
colours[0]is a TypeError). When printed, items may appear in any order — usesorted(s)when the order matters for display.
Like dictionary keys, set items must be immutable: numbers, strings and tuples are fine; lists aren’t.
Removing duplicates
The most common use of a set:
emails = ["a@x.com", "b@x.com", "a@x.com"]
unique = set(emails) # {'a@x.com', 'b@x.com'}
print(len(unique)) # 2 different emailsIf you need to keep the original order, use a dictionary instead (dictionaries keep insertion order and their keys are unique): list(dict.fromkeys(emails)).
Fast membership tests
x in my_list checks items one by one — slow for big lists. x in my_set uses a hash table and takes about the same time whether the set has ten items or ten million:
banned = {"spam", "scam", "phish"}
if word in banned:
print("Blocked")If you check membership many times, convert the list to a set once first.
Changing a set
tags = {"python"}
tags.add("web") # add one item
tags.update(["api", "db"]) # add several
tags.discard("db") # remove if present — no error if not
tags.remove("java") # KeyError: 'java' — use discard if unsure
tags.clear() # empty itSet operations
Sets support the operations from maths, which make comparing groups easy:
| Operator | Method | Result |
|---|---|---|
a | b |
a.union(b) |
items in either |
a & b |
a.intersection(b) |
items in both |
a - b |
a.difference(b) |
in a but not b |
a ^ b |
a.symmetric_difference(b) |
in exactly one |
a <= b |
a.issubset(b) |
is every item of a also in b? |
a >= b |
a.issuperset(b) |
does a contain all of b? |
| — | a.isdisjoint(b) |
do they share nothing? |
python = {"Asha", "Ben", "Chen", "Dee"}
sql = {"Chen", "Dee", "Eli"}
python & sql # {'Chen', 'Dee'}
python - sql # {'Asha', 'Ben'}
sql - python # {'Eli'} — difference depends on the orderThe methods also accept lists: python.intersection(["Chen", "Zoe"]).
Real-world uses
# Which required fields are missing from a form?
required = {"name", "email", "password"}
missing = required - set(form.keys())
# Which products are new this month?
new_products = set(this_month) - set(last_month)
# Do two users have any interests in common?
if user_a_interests & user_b_interests:
print("You might get along!")frozenset
A frozenset is an immutable set. You’ll rarely need it, but it can be a dictionary key or an item of another set: frozenset({"red", "blue"}).
Reach for a set when you hear: “unique”, “distinct”, “already seen”, “in common”, “missing”, or “difference between”.
Course enrolments
Two courses have enrolment lists that contain some duplicates. Using sets: (1) print how many unique students each course has; (2) print, sorted, the students taking both courses; (3) the students taking Python but not SQL; (4) everyone, sorted; (5) the students in exactly one course; (6) check whether all of {"Asha", "Chen"} take Python using a subset test. Finally, remove duplicates from the tags list while keeping the original order (hint: dict.fromkeys).
python = ["Asha", "Ben", "Chen", "Dee", "Asha", "Ben"]
sql = ["Chen", "Dee", "Eli", "Dee"]
tags = ["web", "python", "web", "api", "python", "data"]
# 1–6 with sets
# Remove duplicate tags, keeping orderpython = ["Asha", "Ben", "Chen", "Dee", "Asha", "Ben"]
sql = ["Chen", "Dee", "Eli", "Dee"]
tags = ["web", "python", "web", "api", "python", "data"]
py, sq = set(python), set(sql)
print(len(py), len(sq)) # 4 3
print(sorted(py & sq)) # ['Chen', 'Dee']
print(sorted(py - sq)) # ['Asha', 'Ben']
print(sorted(py | sq)) # ['Asha', 'Ben', 'Chen', 'Dee', 'Eli']
print(sorted(py ^ sq)) # ['Asha', 'Ben', 'Eli']
print({"Asha", "Chen"} <= py) # True
# Remove duplicate tags, keeping order
unique_tags = list(dict.fromkeys(tags))
print(unique_tags) # ['web', 'python', 'api', 'data']Summary
- A set holds unique items with no order:
{1, 2, 3};set()is the empty set ({}is an empty dict). set(items)removes duplicates;x in sis very fast even for huge sets.|union,&intersection,-difference and^symmetric difference compare groups.add,discardandremovechange a set; items must be immutable.- Sets have no positions or order — use
sorted(s)for predictable output, anddict.fromkeysto de-duplicate while keeping order.