frozenset
A frozenset is an immutable version of a set.
Once created, a frozenset cannot be modified, making it safe to use as dictionary keys or elements of other sets.
This topic explains frozenset from basics to advanced use cases.
What Is a frozenset?
A frozenset:
- Is unordered
- Stores unique elements
- Is immutable
- Supports set operations
python
fs = frozenset([1, 2, 3])
print(fs)
frozenset vs set
| Feature | set | frozenset |
|---|---|---|
| Mutable | Yes | No |
| Add / Remove | Allowed | Not allowed |
| Hashable | No | Yes |
| Can be set element | No | Yes |
| Can be dict key | No | Yes |
Creating a frozenset
Using frozenset() Constructor
python
fs = frozenset([1, 2, 3])
print(fs)
From Other Iterables
python
fs = frozenset("Python")
print(fs)
python
fs = frozenset((10, 20, 30))
print(fs)
Empty frozenset
python
empty_fs = frozenset()
print(empty_fs)
Access frozenset Items
frozensets are unordered, so access is done via looping or membership testing.
python
fs = frozenset([1, 2, 3])
for item in fs:
print(item)
python
print(2 in fs)
frozenset Methods
frozensets support read-only set methods.
Common Methods
python
a = frozenset([1, 2, 3])
b = frozenset([3, 4, 5])
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
print(a.symmetric_difference(b))
frozenset Operators
python
print(a | b)
print(a & b)
print(a - b)
print(a ^ b)
frozenset as Dictionary Key
python
data = {
frozenset([1, 2]): "Group A",
frozenset([3, 4]): "Group B"
}
print(data[frozenset([1, 2])])
frozenset Inside a Set
python
s = {frozenset([1, 2]), frozenset([3, 4])}
print(s)
Attempting to Modify frozenset (Not Allowed)
python
fs = frozenset([1, 2, 3])
# fs.add(4) # AttributeError
# fs.remove(2) # AttributeError
frozenset vs Tuple (Common Interview Comparison)
| frozenset | tuple |
|---|---|
| Unordered | Ordered |
| Unique values | Allows duplicates |
| Hashable | Hashable |
| Set operations | No set operations |
When to Use frozenset
Use frozenset when:
- Data must not change
- You need set behavior with immutability
- Using sets as dictionary keys
- Creating nested sets
Common Mistakes
Expecting Order
python
fs = frozenset([1, 2, 3])
print(fs)
Order is not guaranteed.
Expecting Modification
python
# fs.add(5) # Error
Summary
- frozenset is an immutable set
- Stores unique values
- Supports set operations
- Can be dictionary keys
- Ideal for fixed and safe data structures
- Cannot be modified after creation