frozenset in Python with Example

In contrast to set, frozenset is immutable or unchangeable. We use frozenset when we need to create an iterable-like set but with immutable properties.

Note: The frozenset type is equal to the 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 should be:

<class 'frozenset'>

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

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

fs = frozenset(x)
print(fs)

fs[2] = 400
print(fs)

The image below displays an example of the output this Python program produced:

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 allow item assignment")

Now the output should be:

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

The frozenset type object does not allow item assignment

Because the frozenset type is immutable, we can use its items as keys in a dictionary or for any other purpose that the program requires.

Advantages of frozenset in Python

Disadvantages of frozenset in Python

Python Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!