Python frozenset() Function


The Python frozenset() function is a built-in function that returns a new frozenset object containing elements of the given iterable.

python frozenset() function

In Python, sets are implemented in such a way that they don’t allow mutable objects, however, Python sets in themselves are mutable in nature.

So frozensets are just like sets but they can’t be changed. That is, frozensets are the immutable version of Python sets.

Python frozenset() Syntax

frozenset(iterable)

frozenset() takes single parameter.

  • iterable (optional) – It is a sequence from which frozenset is constructed.

It returns an empty frozenset if no parameter is supplied.

Python frozenset() Example

>>> #Empty frozenset()
>>> frozenset()
frozenset()

>>> frozenset([1, 2, 3])
frozenset({1, 2, 3})

>>> frozenset([1, 1, 2, 2, 3])
frozenset({1, 2, 3})

>>> frozenset('example')
frozenset({'l', 'p', 'x', 'm', 'e', 'a'})

>>> #frozenset() and dictionary
>>> frozenset({'a': 1, 'b': 2, 'c': 3})  #takes onl keys
frozenset({'c', 'b', 'a'})

Difference between frozenset() and set() in Python

The difference between set() and frozenset()  in Python is in their mutablity only. frozenset() is immutable and set() is mutable containing immutable objects.

The following example will clarify the difference.

set

>>> num = set([1, 2, 3])
>>> num.add(4)
>>> num
{1, 2, 3, 4}

frozenset

>>> num = set([1, 2, 3])
>>> num.add(4)
Traceback (most recent call last):
 File "<pyshell#17>", line 1, in <module>
 num.add(4)
AttributeError: 'frozenset' object has no attribute 'add'

As you can see in above examples, in set() new elements can be added however, frozenset() being immutable raises an AttributeError when we try to add an element to it.