Frozenset
A frozenset is an immutable set. It supports every read-only set operation and nothing that would change its contents, which makes it hashable and therefore usable as a dictionary key or as a member of another set.
Detailed Explanation
A frozenset is built on the same hash table as a regular set and has the same lookup performance. The difference is what it refuses to do. There is no add, no remove, no update. Once constructed, its contents are fixed for its whole life.
Fixing the contents is what makes the hash meaningful. A set cannot be hashed, because a hash computed today would be wrong tomorrow if someone added an element, and the object would be lost inside whatever hash table was holding it. A frozenset cannot change, so CPython can hash it, cache that hash on the object, and let it act as a key.
That unlocks three patterns you cannot express with a plain set.
First, a set as a dictionary key. You are caching the result of a permission check that depends on which roles a user holds. The roles have no meaningful order, so ("admin", "billing") and ("billing", "admin") should be the same cache entry. frozenset(roles) gives you one canonical key for both.
Second, a set of sets. You are collecting the distinct groups a clustering algorithm produced and want to know how many unique groups there are. A set of frozensets de-duplicates them regardless of the order the members were discovered in.
Third, an undirected edge. In a graph, the edge between "A" and "B" is the same edge as "B" to "A". frozenset({"A", "B"}) normalises the pair, so you can store edge weights in a dict without deciding on an arbitrary ordering.
| Operation | Average | Worst case | Why |
|---|---|---|---|
x in fs | O(1) | O(n) | Hash and probe, identical to set |
len(fs) | O(1) | O(1) | Count is stored |
hash(fs) | O(n) first call, O(1) after | O(n) | Combines element hashes, then caches the result |
fs & other, fs | other, fs - other | same as set | same as set | Same algorithms, new object returned |
fs.add(x) | — | — | Does not exist; frozensets are immutable |
The set operators work across both types, and the result takes the type of the left-hand operand. frozenset({1, 2}) | {3} is a frozenset; {3} | frozenset({1, 2}) is a set. Methods behave the same way, so frozenset({1, 2}).union({3}) returns a frozenset. When a function must return an immutable result, start from the frozenset.
The same shallow-immutability rule applies as for tuples: a frozenset freezes which objects it holds, and it can only hold hashable objects in the first place, so in practice its contents are immutable all the way down. frozenset([[1]]) fails immediately, because a list has no hash.
Use a frozenset for a set-valued constant, for a set that must act as a key, and as a defensive return value when you do not want callers mutating your internal state. Use a plain set everywhere else, since building a frozenset means you cannot grow it incrementally.
Code Examples
# A frozenset is hashable, so a SET of roles can be a dict key.
permission_cache = {}
roles = {"billing", "admin"}
key = frozenset(roles) # canonical, order-independent key
permission_cache[key] = {"read", "write", "refund"}
# A different insertion order produces the same key.
print(frozenset({"admin", "billing"}) == key) # True
print(permission_cache[frozenset(["admin", "billing"])])
# {'read', 'write', 'refund'}
# A mutable set cannot be a key at all.
try:
permission_cache[roles] = set()
except TypeError as exc:
print(exc) # unhashable type: 'set'
# Nothing can modify a frozenset after construction.
print(hasattr(key, "add")) # False# Distinct groups, regardless of the order members were discovered.
raw_clusters = [["u1", "u2"], ["u2", "u1"], ["u3"], ["u3"]]
distinct = {frozenset(group) for group in raw_clusters}
print(len(distinct)) # 2
# Undirected graph edges: one key per pair, either way round.
edge_weight = {
frozenset({"A", "B"}): 4,
frozenset({"B", "C"}): 7,
}
print(edge_weight[frozenset({"B", "A"})]) # 4 <- order does not matter
# Operator results take the type of the LEFT operand.
print(type(frozenset({1, 2}) | {3})) # <class 'frozenset'>
print(type({3} | frozenset({1, 2}))) # <class 'set'>Common Gotchas
In-place operators do not work
`fs |= {"x"}` looks like an update but rebinds the name to a new frozenset, and `fs.update(...)` raises `AttributeError`. If you need to accumulate, build a `set` and freeze it once at the end.
Elements must still be hashable
`frozenset([[1, 2]])` raises `TypeError: unhashable type: 'list'`. Freezing the outer container does not make its contents hashable; convert inner lists to tuples first.
Equal does not mean interchangeable
`frozenset({1, 2}) == {1, 2}` is `True`, but `cache[{1, 2}]` still raises `TypeError`, because a dict must hash the key before it can compare it. Comparing the two types is safe; looking up with the mutable one is not.
Constructing one costs O(n)
`frozenset(items)` builds a whole new hash table. Do it once outside a loop rather than per iteration.