Sub topic 3
Which values can go in a set
This chapter assumes you know Python variables, lists, tuples and dictionaries, and the difference between mutable and immutable objects. It explains which values a set accepts and why.
The rule: elements must be hashable
A set stores each element by its hash, an integer that hash() computes from the value. An object is hashable if it has a hash that never changes during its lifetime and it can be compared with ==. Sets and dict keys both depend on this.
Most immutable built-in types are hashable: int, float, str, bytes, bool, None, frozenset, and tuples whose items are all hashable. Mutable containers such as list, set and dict are not.
def is_hashable(value):
try:
hash(value)
except TypeError:
return False
return True
samples = [42, 3.5, "text", (1, 2), (1, [2]), [1], {1}, {"a": 1}, frozenset({1})]
for value in samples:
print(repr(value), is_hashable(value))The output shows True for 42, 3.5, 'text', (1, 2) and frozenset({1}). It shows False for (1, [2]), [1], {1} and {'a': 1}.
The tuple (1, [2]) fails because a tuple is hashable only if everything inside it is. Its hash is built from the hashes of its items, and the list has none.
Why mutable objects are excluded
A set files each element in a slot chosen by its hash. If an element could change after insertion, its hash would change too. The set would then look in the wrong slot and fail to find an element it actually holds. Python avoids this by refusing mutable built-ins.
When you need a collection as an element, convert it to an immutable form:
groups = {frozenset({1, 2}), frozenset({2, 1})}
print(len(groups)) # 1, equal frozensets are one element
path = [3, 4]
visited = {tuple(path)} # convert a list to a tuple first
print((3, 4) in visited) # TrueEqual values count as one element
A set decides whether two values are duplicates by comparing hashes and then using ==. Numbers that compare equal have equal hashes, so they collapse into a single element:
mixed = {1, 1.0, True}
print(mixed) # {1}
print(len(mixed)) # 1The first value inserted stays. 1, 1.0 and True are all equal, so the set keeps only 1.
Your own classes
A class you write is hashable by default, and two instances are equal only if they are the same object. If you define __eq__ without __hash__, Python sets __hash__ to None and the class becomes unhashable. To make instances with equal contents count as duplicates, define both methods and base the hash on the same fields that __eq__ compares.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
class Broken:
def __eq__(self, other):
return True
print(len({Point(1, 2), Point(1, 2)})) # 1
try:
{Broken()}
except TypeError as e:
print(e) # unhashable type: 'Broken'Common errors
| Error message | Cause | Fix |
|---|---|---|
| `unhashable type: 'list'` | A list was used as an element | Convert it to a tuple |
| `unhashable type: 'set'` | A set was nested inside a set | Use `frozenset` |
| `unhashable type: 'dict'` | A dict was used as an element | Use a tuple of its items, such as `tuple(sorted(d.items()))` |
| `unhashable type: 'Broken'` | The class defined `__eq__` but not `__hash__` | Add a matching `__hash__` |
Exercise
Will {(1, 2), (3, [4])} run, and why? If it fails, which exception does Python raise?
Show answer
It fails with TypeError: unhashable type: 'list'. The tuple (1, 2) is hashable, but (3, [4]) contains a list. A tuple's hash is built from its items' hashes, and the list has none, so the whole tuple is unhashable. Using (3, (4,)) fixes it.
Exercise
A class defines __eq__ comparing two fields, a and b. How should __hash__ be written, and what goes wrong if it hashes only a?
Show answer
Write return hash((self.a, self.b)). Hashing only a still satisfies the rule that equal objects have equal hashes, so it is correct. It is slower, though, because objects that share a but differ in b collide often. Hashing a field that __eq__ ignores would be a real bug, because equal objects could get different hashes.