Skip to content

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 removed
empty = set() # NOT {} — that's an empty dict
s = {1, 2, 3, 4, 5}
# Membership — O(1)
3 in s # True
9 in s # False
# Add / remove
s.add(6)
s.discard(99) # no error if missing
s.remove(1) # KeyError if missing
# Size
len(s) # 5
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 versions
a |= b
a &= b
# Subset / superset
{1, 2} <= {1, 2, 3} # True — subset
{1, 2, 3} >= {1, 2} # True — superset
{1, 2}.isdisjoint({3, 4}) # True — no overlap
squares = {x**2 for x in range(10)}
# {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

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 key
graph = {
frozenset({"A", "B"}): 5, # edge A–B with weight 5
frozenset({"B", "C"}): 3,
}
# Set algebra works the same way
fs | frozenset({4, 5}) # frozenset({1, 2, 3, 4, 5})
Operationsetlist
x in sO(1)O(n)
add / removeO(1)O(n)
union / inter.O(n)O(n²)