frozenset
3 min read ·
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
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
From Other Iterables
Empty frozenset
Access frozenset Items
frozensets are unordered, so access is done via looping or membership testing.
frozenset Methods
frozensets support read-only set methods.
Common Methods
frozenset Operators
frozenset as Dictionary Key
frozenset Inside a Set
Attempting to Modify frozenset (Not Allowed)
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
Order is not guaranteed.