Sub topic 11
frozenset: immutable sets
This chapter assumes you know how set works, including hashability and the set operators from earlier chapters. You should also know the difference between mutable and immutable objects.
What a frozenset is
A frozenset is a set that cannot change after you create it. It supports the same read-only operations as set: membership tests, iteration, len(), the algebra operators and the comparison operators. It has no add, remove, discard, pop, clear or update methods.
The immutability has a useful consequence. A frozenset is hashable, provided all its elements are hashable. A plain set is not hashable, so it cannot be a dict key or a set element. A frozenset can be both.
fs = frozenset([1, 2, 3])
print(2 in fs) # True
lookup = {fs: "numbers"} # a frozenset can be a dict key
print(lookup[frozenset([3, 2, 1])]) # numbers
try:
fs.add(4)
except AttributeError:
print("frozenset has no add method")The lookup works because two frozensets with the same elements are equal and have the same hash, whatever order you wrote them in.
Creating a frozenset
Python has no literal syntax for frozensets. Call the constructor with any iterable. Calling it with no argument gives an empty frozenset.
a = frozenset([3, 1, 2, 3])
print(sorted(a)) # [1, 2, 3]
print(frozenset()) # frozenset()
print(frozenset("hello") == frozenset("olleh")) # TrueA frozenset can hold only hashable elements, so frozenset([[1], [2]]) raises TypeError: unhashable type: 'list'. Use tuples or nested frozensets instead.
Operations and result types
The operators work on frozensets, and you can mix them with sets. The result has the type of the left operand.
fixed = frozenset({1, 2, 3})
mutable = {3, 4}
print(type(fixed | mutable).__name__) # frozenset
print(type(mutable | fixed).__name__) # set
print(sorted(fixed & mutable)) # [3]
print(fixed == {1, 2, 3}) # True, equality ignores the typeThe in-place operators |=, &=, -= and ^= also work on frozensets, but they do not change the object. Python rebinds the name to a new frozenset. Other references to the original object still see the old value.
x = frozenset({1, 2})
y = x
x |= {3}
print(sorted(x)) # [1, 2, 3]
print(sorted(y)) # [1, 2]Where frozensets are useful
Use a frozenset when you need a set-like value that must be hashable or must stay constant.
- A set of sets. Each inner collection must be a frozenset.
- Dict keys. Use a frozenset when the key is "this group of items, in any order".
- Constants. A module-level
frozensettells readers and the interpreter that nobody should modify it.
Undirected graph edges are a good example. The edge from a to b is the same as the edge from b to a, and frozensets treat them as the same.
edges = {frozenset({"a", "b"}), frozenset({"b", "a"}), frozenset({"b", "c"})}
print(len(edges)) # 2
print(frozenset({"c", "b"}) in edges) # TrueCommon errors
try:
bad = {{1, 2}, {3}} # a set cannot contain a set
except TypeError as e:
print(e) # unhashable type: 'set'
good = {frozenset({1, 2}), frozenset({3})}
print(len(good)) # 2Exercise
You want to count how many distinct pairs of friends appear in this list, where ("ann", "bob") and ("bob", "ann") are the same pair: pairs = [("ann", "bob"), ("bob", "ann"), ("cy", "di")]. Which type would you put the pairs into, and what does the count come out as?
Show answer
Convert each pair to a frozenset and collect them in a set: len({frozenset(p) for p in pairs}). The result is 2. Frozensets are hashable, so they can be set elements, and frozenset(("ann", "bob")) == frozenset(("bob", "ann")), so the two orderings collapse into one element.