This is an archived version of the course. Please find the latest version of the course on the main webpage.

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, and it achieves this via hashing. Therefore, the elements in the set must be hashable. This means that you cannot use mutable objects like sets and lists as its element.

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 methods on the previous page (like .add() etc.)