How does frozenset differ from a regular set, and what specific use case does its immutability enable?
Short answer
frozenset is an IMMUTABLE version of set — once created, it can't be modified, which (like tuples) makes it HASHABLE and therefore usable as a dictionary key or as an element of another set, something a regular mutable set cannot do.
Advertisement
AModel answer
frozenset is an IMMUTABLE version of set — once created, it can't be modified, which (like tuples) makes it HASHABLE and therefore usable as a dictionary key or as an element of another set, something a regular mutable set cannot do.
regular_set = {1, 2, 3}
# hash(regular_set) # TypeError: unhashable type: 'set'
frozen = frozenset([1, 2, 3])
print(hash(frozen)) # works fine
cache = {frozen: "cached result"} # usable as a dict keyReal-world example
Using a frozenset of tags or permissions as a dictionary key to cache results based on that exact combination.
Likely follow-ups
- Can you still perform set operations like union() and intersection() on a frozenset, or only mutation methods are disallowed?
Related topics