Frozenset in Python
Overview
A frozenset is an immutable and hashable version of a set in Python. Unlike regular sets, frozensets cannot be modified after creation, which allows them to be members of other sets. This immutability makes them useful when you need a set that should not change. Because sets aren’t immutable and hashable, they can’t belong to other sets. To remedy that situation, Python has another set type, frozenset, which is just like a set but can’t be changed after creation. Because frozensets are immutable and hashable, they can be members of other sets.
Example Usage
Below is an example demonstrating the creation of a frozenset from a regular set and attempting to modify it:
x = set([1, 2, 3, 1, 3, 5])
z = frozenset(x)
z
frozenset({1, 2, 3, 5})
z.add(6)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-60917eecf5a3> in <cell line: 1>()
----> 1 z.add(6)
AttributeError: 'frozenset' object has no attribute 'add'
x.add(z)
x
{1, 2, 3, 5, frozenset({1, 2, 3, 5})}
Explanation
-
Creation of a Set: We start by creating a set
xwith some duplicate elements. The duplicates are automatically removed, resulting in{1, 2, 3, 5}. -
Conversion to Frozenset: We then convert this set
xinto afrozensetnamedz. Thefrozensetcontains the same elements as the set, but it is immutable. -
Attempt to Modify Frozenset: When we try to add an element
6to thefrozensetz, anAttributeErroris raised becausefrozensetobjects do not support item addition. -
Frozenset as a Set Member: Finally, we add the
frozensetzto the original setx. This operation is successful becausefrozensetis immutable and hashable, allowing it to be a member of another set. The resulting setxnow contains the original elements along with thefrozenset:{1, 2, 3, 5, frozenset({1, 2, 3, 5})}.
FAQ (Frequently asked questions)
What is a frozenset in Python?
Can frozensets be modified after creation?
Why are frozensets useful?
Can frozensets be members of other sets?
How do you create a frozenset from a set in Python?
What happens if you try to add an element to a frozenset?
Can a frozenset be added to a regular set?