Dictionaries and sets
Sets
Goal: Remove duplicates and combine collections with union, intersection and difference · 10 min
A set is an unordered collection of unique items: tags = {"python", "code", "python"} contains just two items. Create an empty set with set() (not {}, which is an empty dictionary).
Uses:
- Remove duplicates:
set([3, 1, 3, 2, 1])→ {1, 2, 3}. The original order is lost; usesorted(set(x))for a sorted unique list. - Fast membership:
x in my_setis fast even for millions of items, while a list must be searched one by one.
Changing: add(x), remove(x) (KeyError if absent), discard(x) (no error). Because sets are unordered there is no indexing and no slicing.
Set algebra compares collections:
| operator | method | meaning | |
|---|---|---|---|
| `a | b` | a.union(b) | in a or b |
a & b | a.intersection(b) | in both | |
a - b | a.difference(b) | in a but not in b | |
a ^ b | a.symmetric_difference(b) | in exactly one of them | |
a <= b | a.issubset(b) | every item of a is in b |
Example: {1, 2, 3} & {2, 3, 4} is {2, 3}. A set comprehension looks like a list comprehension with braces: {len(w) for w in words}.
Because the order of a set is not guaranteed, always sort before printing if you need stable output: print(sorted(s)).
Worked example: Who attended both days?
- mon = {"Ada", "Alan", "Grace"}; tue = {"Alan", "Grace", "Linus"}.
- Both days: mon & tue = {Alan, Grace}. Only Monday: mon - tue = {Ada}.
- Anyone present at least once: mon | tue (4 people).
mon = {"Ada", "Alan", "Grace"}
tue = {"Alan", "Grace", "Linus"}
print(sorted(mon & tue))
print(sorted(mon - tue))
print(len(mon | tue))Output:
['Alan', 'Grace']
['Ada']
4