Lesson 8
Making Objects the Main Star!
Chapter 2: Set
Frozen set
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 frozenset
s 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.)