What is the frozenset() method in Python?

Overview

The frozenset() method is an inbuilt function in Python that converts an iterable object into an immutable object.

Syntax

The syntax of this method is as follows:

frozenset([iterable_object])

Parameter

The frozenset() function takes one optional parameter, an iterable object.

Return value

The return value is an immutable iterable object.

Example 1

When frozenset() is provided no parameter, it returns as it is without raising any error:

# no parameter
f_set0 = frozenset()
print('The frozen set with no parameter:', f_set0)
# set
integers = {1, 2, 3, 4, 5}
f_set1 = frozenset(integers)
f_set1.add(10)
print('The frozen set is:', f_set1)

Example 2

In the second example, f_set1 becomes unmodifiable by the application of frozenset() to integers. This is why, when a number is tried to be added to f_set1, it does not recognize the attribute add:

# list
bands = ['BTS', '1D', 'GOT7', 'TXT']
f_set2 = frozenset(bands)
f_set2.append('NCT')
print('The frozen set is:', f_set2)

Similarly, frozenset() makes f_set2 unmodifiable and hence it raises the AttributeError.

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources