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

  1. Creation of a Set: We start by creating a set x with some duplicate elements. The duplicates are automatically removed, resulting in {1, 2, 3, 5}.

  2. Conversion to Frozenset: We then convert this set x into a frozenset named z. The frozenset contains the same elements as the set, but it is immutable.

  3. Attempt to Modify Frozenset: When we try to add an element 6 to the frozenset z, an AttributeError is raised because frozenset objects do not support item addition.

  4. Frozenset as a Set Member: Finally, we add the frozenset z to the original set x. This operation is successful because frozenset is immutable and hashable, allowing it to be a member of another set. The resulting set x now contains the original elements along with the frozenset: {1, 2, 3, 5, frozenset({1, 2, 3, 5})}.