frozenset()
The immutable sibling of set — same operations minus mutation, plus hashability.
Demo
frozenset takes an iterable and stores its UNIQUE elements — duplicates collapse, exactly like set. The result is IMMUTABLE: no add, no discard, no clear. Because it is immutable, it is hashable — you can use a frozenset as a dict key or put it inside another set. That is the primary reason to prefer it over set. The display order is not meaningful (set element order is arbitrary).
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| iterable | iterable | no (()) | Any iterable — the frozenset takes the unique elements. Empty or omitted → an empty frozenset. |
Return value
frozenset — An immutable set containing the unique elements of iterable. Supports all read operations of set (union, intersection, contains, len, iteration) but none of the mutations (add, discard, clear, update). Hashable, so it can be a dict key or a member of another set.
Common patterns
ALLOWED_METHODS = frozenset({"GET", "POST", "PUT"})
cache = {} cache[frozenset({"user", "admin"})] = compute(...)
clusters = {frozenset({"a", "b"}), frozenset({"c", "d"})}
frozenset({1,2}) | frozenset({2,3}) # frozenset({1,2,3})
Examples
Pitfalls
fs = frozenset([1, 2]) fs.add(3)
fs2 = fs | {3}
fs = frozenset({1, 2}) fs.copy() is fs
fs.copy() == fs
frozenset([[1, 2], [3, 4]])
frozenset([(1, 2), (3, 4)])
frozenset() # display
# same reason set() displays as set(), not {}When to use
- A set that must be a dict key or an element of another set
- Module-level constants that should not accidentally mutate
- Cache keys that involve set membership
- Data-model IDs that need value semantics but include an unordered subset
- You will add or remove elements → use set
- Element order matters → sets (frozen or not) do not guarantee order
- Only reading, single-use → set is fine
- Small fixed-membership check → a tuple can be faster for small sizes
Notes
FAQ
set is mutable — supports add, discard, clear, update. frozenset is immutable — no mutation methods. frozenset is hashable (usable as dict key or set element); set is not. Both share all read operations and set-algebra methods.