Python frozenset()

The frozenset() method returns an immutable frozenset object initialized with elements from the given iterable.

Frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, elements of frozen set remains the same after creation.

Due to this, frozen sets can be used as key in Dictionary or as element of another set. But like sets, it is not ordered (the elements can be set at any index).

The syntax of frozenset() method is:

frozenset([iterable])

frozenset() Parameters

The frozenset() method optionally takes a single parameter:

  • iterable (Optional) - the iterable which contains elements to initialize the frozenset with.
    Iterable can be set, dictionary, tuple, etc.

Return value from frozenset()

The frozenset() method returns an immutable frozenset initialized with elements from the given iterable.

If no parameters are passed, it returns an empty frozenset.


Example 1: How frozenset() works in Python?

# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')

fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())

When you run the program, the output will be:

The frozen set is: frozenset({'i', 'a', 'u', 'e', 'o'})
The empty frozen set is: frozenset()

Example 2: frozenset() for Dictionary

When you use dictionary as an iterable for a frozen set. It only takes key of the dictionary to create the set.

# random dictionary
person = {"name": "John", "age": 23, "sex": "male"}

fSet = frozenset(person)
print('The frozen set is:', fSet)

When you run the program, the output will be:

The frozen set is: frozenset({'name', 'sex', 'age'})

Frozenset operations

Like normal sets, frozenset can also perform different operations like union, intersection, etc.