Python Basics — Frozenset
Frozenset
A frozenset is an immutable version of a set. Once created, you cannot add, remove, or modify its elements.
Creating Frozensets
fs = frozenset([1, 2, 3, 2, 1])
print(fs) # frozenset({1, 2, 3})
print(type(fs)) # <class 'frozenset'>
# From a set
s = {4, 5, 6}
fs = frozenset(s)
print(fs) # frozenset({4, 5, 6})
# Empty frozenset
empty = frozenset()
print(empty) # frozenset()
Immutability
fs = frozenset([1, 2, 3])
# ❌ All mutation methods are unavailable
# fs.add(4) # AttributeError
# fs.remove(1) # AttributeError
# fs.discard(2) # AttributeError
# fs.pop() # AttributeError
# fs.clear() # AttributeError
Frozenset as Dictionary Key
Since frozensets are hashable (immutable), they can be used as dictionary keys:
# Group permissions
permissions = {
frozenset({"read"}): "viewer",
frozenset({"read", "write"}): "editor",
frozenset({"read", "write", "admin"}): "admin",
}
user_perms = frozenset({"read", "write"})
print(permissions[user_perms]) # editor
Frozenset as Set Element
A frozenset can be an element of another set:
# Set of sets (using frozensets)
groups = {
frozenset({1, 2}),
frozenset({3, 4}),
frozenset({1, 2}), # duplicate — removed
}
print(groups)
# {frozenset({3, 4}), frozenset({1, 2})}
You cannot put a regular set inside another set because sets are mutable (unhashable).
Frozenset Operations
All non-mutating set operations work:
a = frozenset({1, 2, 3})
b = frozenset({3, 4, 5})
print(a | b) # frozenset({1, 2, 3, 4, 5})
print(a & b) # frozenset({3})
print(a - b) # frozenset({1, 2})
print(a ^ b) # frozenset({1, 2, 4, 5})
print(a.issubset(b)) # False
print(a.isdisjoint(b)) # False
Operations between set and frozenset return the type of the left operand:
s = {1, 2, 3}
fs = frozenset({3, 4, 5})
result1 = s | fs
print(type(result1)) # <class 'set'>
result2 = fs | s
print(type(result2)) # <class 'frozenset'>
When to Use Frozenset vs Set
| Use Frozenset When… | Use Set When… |
|---|---|
| Need hashable set (dict key) | Need to add/remove elements |
| Need set as element of another set | Data will change over time |
| Want to ensure immutability | Working with dynamic collections |
| Representing constants | Normal set operations with mutations |
Summary
frozenset()creates an immutable set- Cannot add, remove, or modify elements
- Hashable — can be dict keys or set elements
- Supports all read-only set operations (union, intersection, etc.)
- In-place operations (
update,add,remove) are not available - Operations between set and frozenset return the left operand’s type
Next up: Set Comprehensions →