Sets & Frozensets
A set stores unique, unordered values. The key capability it adds over a list is O(1) membership testing and set algebra (union, intersection, difference).
primes = {2, 3, 5, 7, 11}letters = set("hello") # {"h", "e", "l", "o"} — duplicates removedempty = set() # NOT {} — that's an empty dictCore operations
Section titled “Core operations”s = {1, 2, 3, 4, 5}
# Membership — O(1)3 in s # True9 in s # False
# Add / removes.add(6)s.discard(99) # no error if missings.remove(1) # KeyError if missing
# Sizelen(s) # 5Set algebra
Section titled “Set algebra”a = {1, 2, 3, 4}b = {3, 4, 5, 6}
a | b # union → {1, 2, 3, 4, 5, 6}a & b # intersection → {3, 4}a - b # difference → {1, 2} (in a but not b)a ^ b # symmetric ∆ → {1, 2, 5, 6} (in one but not both)
# In-place versionsa |= ba &= b
# Subset / superset{1, 2} <= {1, 2, 3} # True — subset{1, 2, 3} >= {1, 2} # True — superset{1, 2}.isdisjoint({3, 4}) # True — no overlapSet comprehensions
Section titled “Set comprehensions”squares = {x**2 for x in range(10)}# {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}frozenset
Section titled “frozenset”An immutable set. Since it is hashable, it can be used as a dictionary key or stored inside another set.
fs = frozenset({1, 2, 3})
# Can be a dict keygraph = { frozenset({"A", "B"}): 5, # edge A–B with weight 5 frozenset({"B", "C"}): 3,}
# Set algebra works the same wayfs | frozenset({4, 5}) # frozenset({1, 2, 3, 4, 5})Complexity at a glance
Section titled “Complexity at a glance”| Operation | set | list |
|---|---|---|
x in s | O(1) | O(n) |
add / remove | O(1) | O(n) |
| union / inter. | O(n) | O(n²) |