12.11 Frozen Sets
frozenset -- the immutable counterpart to set -- same union/intersection/membership behavior, but no add(), remove(), or update(), which is exactly what makes it hashable and usable as a dict key or set member.
Same operations as a regular set — union, intersection, membership — minus mutability.
What Is frozenset?
The immutable counterpart to set — same union/intersection/membership behavior, but no add(), remove(), or any method that would modify it. Because it’s immutable, it’s hashable, and therefore usable as a dict key or as a member of another set (which a regular set can never be) — the exact same trade-off covered for tuples in 11.9 Immutability and Copying.
Creating frozensets
>>> fs = frozenset([1, 2, 3])
>>> fs
frozenset({1, 2, 3})
Advantages
>>> fs.add(4)
Traceback (most recent call last):
AttributeError: 'frozenset' object has no attribute 'add'
>>> hash(fs) # hashable -- a regular set is NOT
-272375401224217160
>>> d = {fs: "value"} # usable as a dict key
>>> d
{frozenset({1, 2, 3}): 'value'}
Use Cases
- A fixed set of valid options that should never change at runtime
- A set-of-sets, since a
frozensetcan be a member of another set - A dict key representing a group/combination of values
Quick Interview Answer
“
frozensetis tosetwhat a tuple is to a list: the same core behavior — union, intersection, membership — with mutation removed. That single change is what makes it hashable, and hashability is the whole payoff: afrozensetcan be a dict key or a member of another set, both of which are flatly impossible for a regularset, sinceset.__hash__doesn’t exist. The natural use case is a fixed group of values that itself needs to act like a value — a set-of-sets, or a dict key representing some combination.”
Common Mistakes
- Trying
fs.add(x)orfs.remove(x)on afrozenset— neither exists;AttributeErroris raised immediately, the same shape of mistake as calling.append()on a tuple. - Reaching for a regular
setas a dict key or set member and hittingTypeError: unhashable type: 'set'— swap infrozensetinstead. - Assuming
frozensetandtupleare interchangeable for “an immutable collection” — afrozensetstill deduplicates and is unordered; a tuple preserves order and duplicates. Pick based on which behavior is actually needed.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form