Language: EN

python-frozen-set

Using Frozen Sets in Python

A frozen set in Python is a unordered and immutable collection of unique elements. It behaves similarly to a set (set), but cannot be modified once created.

That is, once created we cannot add or remove elements, nor modify the existing ones (attempting to add, remove, or modify elements will raise an error).

Just like set, frozenset can only contain unique elements. Duplicate elements are automatically removed.

Also similar to set, the elements within a frozenset do not have a specific order (therefore, elements cannot be accessed by index, unlike lists).

Frozen sets are useful when we need a collection of unique elements that will not be modified during the execution of the program. For example, as keys in a dictionary or to be included in other sets (since both need hashable and immutable values)

Creating Frozen Sets

Frozen sets are created using the frozenset() function and can contain elements of any hashable type.

# Create a frozenset from a list
immutable_set = frozenset([1, 2, 3, 4, 5])
print(immutable_set)  # Output: frozenset({1, 2, 3, 4, 5})

# Create a frozenset from a list of strings
fruits = frozenset(["apple", "banana", "orange"])

print(fruits)  # Output: frozenset({'apple', 'banana', 'orange'})

# Create a frozenset from a set
mutable_set = {1, 2, 3, 4, 5}
immutable_set = frozenset(mutable_set)
print(immutable_set)  # Output: frozenset({1, 2, 3, 4, 5})

# Create a frozenset from a string
immutable_set = frozenset('python')
print(immutable_set)  # Output: frozenset({'p', 'y', 't', 'h', 'o', 'n'})

Operations with FrozenSet

Despite its immutability, frozenset allows for several set operations such as union, intersection, and difference.

# Create two frozensets
set_a = frozenset([1, 2, 3])
set_b = frozenset([3, 4, 5])

# Union of frozensets
union_set = set_a | set_b
print(union_set)  # Output: frozenset({1, 2, 3, 4, 5})

# Intersection of frozensets
intersection_set = set_a & set_b
print(intersection_set)  # Output: frozenset({3})

# Difference of frozensets
difference_set = set_a - set_b
print(difference_set)  # Output: frozenset({1, 2})

# Symmetric difference of frozensets
symmetric_difference_set = set_a ^ set_b
print(symmetric_difference_set)  # Output: frozenset({1, 2, 4, 5})

# Check if one frozenset is a subset of another
isSubset = frozenset([3, 4]) < set_b
print(isSubset)  # True

Although frozenset allows basic set operations, it does not support methods that modify the set, such as add(), remove(), or discard().

Practical Examples