Frozensets in Python

What is a Frozenset?

A frozenset is an immutable version of a set in Python. Like sets, frozensets are unordered collections of unique elements. However, unlike sets, frozensets cannot be modified after creation—no elements can be added or removed.

Creating Frozensets

my_frozenset = frozenset([1, 2, 3, 2])
print(my_frozenset)  # Output: frozenset({1, 2, 3})

Examples

# 1. Creating and printing a frozenset
colors = frozenset(["red", "green", "blue"])
print(colors)  # Output: frozenset({'red', 'green', 'blue'})
  
# 2. Attempting to add an element (will raise an error)
colors.add("yellow")  # AttributeError: 'frozenset' object has no attribute 'add'
  
# 3. Using frozensets as dictionary keys (allowed because they are immutable)
fs1 = frozenset([1, 2])
fs2 = frozenset([3, 4])
my_dict = {fs1: "a", fs2: "b"}
print(my_dict)
  
# 4. Frozenset operations: union and intersection
a = frozenset([1, 2, 3])
b = frozenset([3, 4, 5])
print(a.union(b))        # Output: frozenset({1, 2, 3, 4, 5})
print(a.intersection(b)) # Output: frozenset({3})
  
# 5. Checking membership
print("red" in colors)  # Output: True