Python frozenset

Unlike set, frozenset type is an immutable or an unchangeable. We use frozenset when we need to create an iterable like set, but with immutable property.

Note - The frozenset type is equal to set type in Python, except that, it is immutable, whereas set is mutable.

Let's create a program that creates a frozenset type object named fs and prints its type using the type function:

x = [12, 43, 5, 64]
fs = frozenset(x)
print(type(fs))

The output will be:

<class 'frozenset'>

Because the frozenset type object is immutable, therefore let's create a program to demonstrates this property by changing the element:

x = [12, 43, 5, 64, 32, 55]

fs = frozenset(x)
print(fs)

fs[2] = 400
print(fs)

The snapshot given below shows the sample output produced by this Python program:

python frozenset

That is, the code, fs[2] = 400 raised an exception named TypeError, saying that the object frozenset does not support item assignment. The exception can be caught using the try-except block, as shown in the program given below:

x = [12, 43, 5, 64, 32, 55]

fs = frozenset(x)
print(fs)

try:
    fs[2] = 400
    print(fs)
except TypeError:
    print("\nThe frozenset type object does not allows item assignment")

Now the output would be:

frozenset({64, 32, 5, 43, 12, 55})

The frozenset type object does not allows item assignment

Because frozenset type is immutable, therefore we can use its item as keys of dictionary or for any other purpose, depending on the requirement of the program.

Python Online Test


« Previous Tutorial Next Tutorial »