Frozenset

Python provides another built-in type called a frozenset. Frozensets are exactly the same as set in all aspects except that they are immutable. You can perform all operations similar to sets except change or modifying operations such as add() and update().

You can create a frozenset with frozenset(<iter>) method.

frozen_set = frozenset((2, 3, 4, 5))
print(frozen_set)

Outputs:

# print(frozen_set)
frozenset({2, 3, 4, 5})

# print(type(frozen_set))
<class 'frozenset'>

Frozensets are useful in situations where you want to use a set, but you need an immutable object. For example, you can’t define a set whose elements are also sets, because set elements must be immutable:

set1 = set(['Krakow'])
set2 = set(['Warsaw'])
set3 = set(['Kielce'])
new_set = {set1, set2, set3}

Outputs:

TypeError                                 Traceback (most recent call last)
<ipython-input-24-8310bd641e86> in <module>()
      2 set2 = set(['bar'])
      3 set3 = set(['baz'])
----> 4 new_set = {set1, set2, set3}

TypeError: unhashable type: 'set'

Sometimes, it happens that you need to define a set of sets, you can create set of sets if the elements are frozensets because frozensets are immutable.

set1 = frozenset(['Krakow'])
set2 = frozenset(['Warsaw'])
set3 = frozenset(['Kielce'])
new_set = {set1, set2, set3}

print(new_set)

Outputs:

{frozenset({'Kielce'}), frozenset({'Warsaw'}), frozenset({'Krakow'})}