frozenset supports every read-only set operation — membership testing, union, intersection, difference — but has no add(), remove(), or other mutating methods, since it's immutable by design. That immutability is exactly what makes a frozenset itself hashable, which means, unlike a regular set, a frozenset can be used as a dictionary key or stored as an element inside another set.
1Understanding Frozensets
frozenset supports every read-only set operation — membership testing, union, intersection, difference — but has no add(), remove(), or other mutating methods, since it's immutable by design. That immutability is exactly what makes a frozenset itself hashable, which means, unlike a regular set, a frozenset can be used as a dictionary key or stored as an element inside another set.
Reach for frozenset specifically when you need a set-like value to act as a dictionary key or as a member of another set — a plain set will raise a TypeError in both of those situations.
fs = frozenset([1, 2, 2, 3])
print(fs)
print(1 in fs)2Practical Example
Here is a real-world application of Frozensets showing how it is used in production Python code.
cache = {}
key = frozenset({"width": 10, "height": 20}.items())
cache[key] = "computed result"
print(cache[key])3Best Practices
Follow these guidelines when working with Frozensets:
1. Use frozenset instead of set whenever the collection needs to be hashable, such as for a dictionary key
2. Convert a frozenset to a regular set with set(fs) if you need to mutate it later
3. Use frozenset for representing an immutable configuration or constant collection, signaling to readers it won't change
Tip: Reach for frozenset specifically when you need a set-like value to act as a dictionary key or as a member of another set — a plain set will raise a TypeError in both of those situations.
fs = frozenset([1, 2, 2, 3])
print(fs)
print(1 in fs)