Sets
Frozen Sets
Immutable sets
Interview: Tests understanding of hashability and immutable data structures
A frozenset is an immutable version of a set. Like tuples are to lists, frozensets are to sets — same operations but cannot be modified after creation. Because they're immutable and hashable, frozensets can be used as dictionary keys and elements of other sets.
Properties
- Immutable: Cannot add, remove, or modify elements
- Hashable: Can be used as dict keys and set members (regular sets cannot)
- Supports all read operations: Membership, len, iteration, set operations (|, &, -, ^)
- Set operations return frozensets: If either operand is a frozenset, the result is a frozenset
When to Use Frozensets
- Set of sets:
{frozenset({1,2}), frozenset({3,4})} - Dictionary keys: When you need a set-like key
- Memoization: As cache keys for functions that take set arguments
- Data integrity: When a set should not be modified
Performance
Frozensets have the same O(1) membership testing as regular sets. Their hash is computed once at creation and cached, making them efficient as dict keys.
Use Cases
Using sets as dictionary keys
Creating sets of sets (nested set structures)
Memoization/caching for functions that take set arguments
Immutable permission groups and configuration constants
Common Mistakes
Trying to modify a frozenset (add/remove) — it raises AttributeError
Using frozenset when a regular set suffices (unnecessary constraint)
Forgetting that frozenset elements must also be hashable
Not knowing that frozenset({1,2}) == frozenset([1,2]) — order doesn't matter