Chapter 2: Set

Frozen set

face Josiah Wang

What happens when you run the following? Does it work?

>>> numbers = {{1,2}, {3,4}} 
???

Remember that a set need to ensure that its elements are unique, i.e. without any duplicates. It achieves this via hashing. Therefore, each element in the set must be hashable. This means that you cannot use mutable objects like lists and sets as its element (because these can be modified).

Python provides a variant of set called frozenset that is immutable (and hashable). Such frozensets are useful if you need a set inside a set.

>>> numbers = {frozenset({1,2}), frozenset({3,4})} 
>>> print(numbers)
{frozenset({3, 4}), frozenset({1, 2})}

Since frozenset is immutable, you cannot use the mutator methods on the previous page (like .add() etc.)