PYTHON
Using `frozenset` for Immutable Set Keys and Membership Testing
Explore `frozenset` in Python to create immutable sets, enabling their use as dictionary keys or for efficient, hashable collections in various data structures.
# Create frozenset instances
fs1 = frozenset([1, 2, 3])
fs2 = frozenset([3, 2, 1])
fs3 = frozenset([1, 2, 4])
print(f"fs1: {fs1}")
print(f"fs2: {fs2}")
print(f"fs3: {fs3}")
# Frozensets are hashable, so they can be used as dictionary keys
data_map = {}
data_map[fs1] = "Set One"
data_map[fs3] = "Set Three"
print(f"
Value for fs1 (which is equivalent to fs2): {data_map[fs2]}")
# Demonstrate immutability (no add/remove methods)
try:
fs1.add(4)
except AttributeError as e:
print(f"
Error trying to modify frozenset: {e}")
# Membership testing is efficient
if 2 in fs1:
print("
2 is in fs1")
How it works: A `frozenset` is an immutable version of a Python `set`. Because it is immutable, a `frozenset` is hashable, meaning it can be used as a key in a dictionary or as an element in another set. This is particularly useful when you need to store a collection of unique items (where order doesn't matter) and treat that collection itself as a distinct, unchangeable entity for lookup or comparison, enhancing performance in specific data structure patterns.