Understanding Python frozenset: Immutable Sets and Their Operations
This article explains Python's frozenset type, detailing its immutable nature, creation syntax, differences from mutable sets, supported operations, membership testing, and practical code examples illustrating set algebra and method usage.
The frozenset() function creates an immutable set in Python; once created, elements cannot be added or removed. Its syntax is frozenset([iterable]) , where the optional iterable can be any iterable object such as a list, tuple, or string. If no argument is provided, an empty frozenset is returned.
Example usage:
a = frozenset(range(10)) b = frozenset('runoob')
Key differences between set (mutable) and frozenset (immutable): mutable sets support methods like add() and remove() , have no hash value, and cannot be used as dictionary keys, whereas frozensets are hashable and can serve as keys or elements of other sets. Frozensets lack methods that modify the collection.
Creating sets and frozensets:
s = set([1, 2, 3]) t = frozenset('bookshop')
Mutable sets can be updated with add() , update() , remove() , etc., while attempts to call these on a frozenset raise AttributeError .
Membership tests ( in / not in ) work the same for both types:
'k' in s # False 'h' in s # True 'k' in t # True
Set algebra operators are supported for both types, producing results whose type matches the left operand:
Union ( | ), intersection ( & ), difference ( - ), and symmetric difference ( ^ ) examples:
s | t yields a set when s is the left operand, and a frozenset when t is left.
Both set and frozenset support built‑in functions and methods such as len() , copy() , and the various update methods ( update() , intersection_update() , difference_update() , symmetric_difference_update() ) for mutable sets.
Iteration over elements works for both types:
for i in s: print(i) and for i in t: print(i) produce the elements in arbitrary order.
Overall, frozenset provides a hashable, read‑only collection useful for dictionary keys and set operations where immutability is required.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.