The frozenset()
function creates a set that cannot be modified. It’s useful when you need unchangeable, hashable sets for dictionary keys, set operations, or security reasons.
Example
numbers = frozenset([1, 2, 3, 4, 5])
print(numbers)
# Output: frozenset({1, 2, 3, 4, 5})
A regular set allows modification, but frozenset()
makes it immutable.
Syntax
frozenset(iterable)
- iterable → Any sequence (list, tuple, set, etc.).
- Returns → An unchangeable set.
1. Preventing Accidental Modifications
data = frozenset(["apple", "banana", "cherry"])
# data.add("orange") # ❌ Error! Frozenset is immutable.
This ensures data integrity in large programs.
2. Using frozenset()
as Dictionary Keys
Because frozenset
is hashable, it can be a dictionary key.
mapping = {frozenset(["red", "blue"]): "Colors"}
print(mapping[frozenset(["red", "blue"])])
# Output: Colors
Great for storing unique combinations of values.
3. Performing Set Operations
frozenset()
supports union, intersection, and difference.
a = frozenset([1, 2, 3])
b = frozenset([2, 3, 4])
print(a | b) # Union → frozenset({1, 2, 3, 4})
print(a & b) # Intersection → frozenset({2, 3})
print(a - b) # Difference → frozenset({1})
Useful when you need immutable mathematical sets.
4. Storing Unique Immutable Sets in Another Set
You cannot add normal sets inside sets, but you can add frozensets.
unique_sets = {frozenset([1, 2]), frozenset([3, 4])}
print(unique_sets)
# Output: {frozenset({1, 2}), frozenset({3, 4})}
This allows grouping of unique, unchangeable data.
Key Notes
- ✔ Immutable version of a set – prevents accidental modifications.
- ✔ Can be used as dictionary keys – unlike regular sets.
- ✔ Supports set operations (union, intersection, etc.).
- ✔ Can be stored inside other sets – unlike normal sets.
By using frozenset()
, you can protect data, improve efficiency, and use sets in places where normal sets aren’t allowed. 🚀