Sub topic 3
Which Values Can Go in a Set
This chapter assumes you know how to create sets, the difference between mutable and immutable objects, and basic class syntax (__init__, __eq__). It explains the rule that decides whether a value can be a set element, why the rule exists, and what to do when a value fails it.
The rule: elements must be hashable
Every element of a set must be hashable. An object is hashable if it has a hash value that never changes during its lifetime (__hash__) and can be compared to other objects with == (__eq__). Objects that compare equal must have the same hash value.
points = {(1, 2), (3, 4)} # tuples are hashable
print((1, 2) in points) # True
try:
bad = {[1, 2], [3, 4]} # lists are not hashable
except TypeError as e:
print(e) # unhashable type: 'list'The error appears when Python tries to put the element into the set. The set calls hash() on each element to decide where to store it, and hash() raises TypeError for unhashable objects.
Why the rule exists
A set stores elements in a hash table. The hash value picks a slot, so a lookup jumps straight to the right place instead of scanning every element. This only works if an element's hash stays the same while it is in the set. A mutable object whose contents change would have a different hash later, and the set could no longer find it.
Python's answer is to make the built-in mutable containers unhashable. Immutable values keep one hash for their whole life.
Built-in types
| Type | Hashable? | Note |
|---|---|---|
| `int`, `float`, `complex`, `bool` | Yes | Numbers that compare equal hash equally |
| `str`, `bytes` | Yes | |
| `None`, `range` | Yes | |
| `tuple` | Only if every item is | Hashability depends on the contents |
| `frozenset` | Yes | The hashable version of a set |
| `list`, `dict`, `set`, `bytearray` | No | Mutable containers |
| functions, classes, modules | Yes | Hashed by identity |
Tuples depend on their contents
A tuple is immutable, but it can hold a mutable object. Its hash is computed from the hashes of its items, so one list inside makes the whole tuple unhashable.
try:
nested = {(1, [2, 3])}
except TypeError as e:
print(e) # unhashable type: 'list'This also affects type checks. isinstance(x, Hashable) only checks that the type defines __hash__. It does not hash the object.
from collections.abc import Hashable
t = (1, [2])
print(isinstance(t, Hashable)) # True, tuple defines __hash__
try:
hash(t)
except TypeError:
print("hash() still fails") # the list inside breaks itTo test whether a value can really go in a set, call hash(value) inside a try block.
Equal values collapse into one element
A set treats two elements as the same when their hashes match and they compare equal. For numbers, this has surprising consequences.
s = {1, 1.0, True}
print(s) # {1}
print(len({0, False, 0.0})) # 1
print(hash(1) == hash(1.0) == hash(True)) # True1 == 1.0 == True in Python, so only the first inserted value survives. The same happens with dictionary keys. Be careful when you store mixed data, such as flags and counts, in one set.
NaN
float("nan") is not equal to itself, yet it can be in a set. Before calling ==, a set checks whether the two objects are the same object (is). That check decides the result here.
nan = float("nan")
print(len({nan, nan})) # 1, same object
print(len({float("nan"), float("nan")})) # 2, two different objects
print(nan in {nan}) # True, identity match
print(float("nan") in {nan}) # False, different objectAvoid NaN in sets. If you have to deal with it, filter it out before building the set.
Custom classes
By default, instances of your own classes are hashable, and the hash is based on identity. Two separate instances are never equal, even with identical attributes.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
q = Point(1, 2)
print(p == q) # False
print(len({p, q})) # 2If you want value-based behavior, define __eq__. Doing that alone has a side effect: Python sets __hash__ to None, so the class becomes unhashable.
class Bad:
def __init__(self, x):
self.x = x
def __eq__(self, other):
return isinstance(other, Bad) and self.x == other.x
try:
{Bad(1)}
except TypeError as e:
print(e) # unhashable type: 'Bad'Python does this on purpose. A class that changes what "equal" means must also say how to hash, or equal objects could land in different slots. 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
@property
def x(self):
return self._x
@property
def y(self):
return self._y
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self._x, self._y) == (other._x, other._y)
def __hash__(self):
return hash((self._x, self._y))
print(len({Point(1, 2), Point(1, 2)})) # 1The read-only properties signal that the fields should not change. A frozen dataclass does the same with less code. It generates __eq__ and __hash__ and blocks attribute assignment.
from dataclasses import dataclass
@dataclass(frozen=True)
class Pt:
x: int
y: int
print(len({Pt(1, 2), Pt(1, 2)})) # 1Mutating an element after insertion
Python cannot stop you from building a class whose hash depends on a field you later change. The set will not notice.
class Box:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return isinstance(other, Box) and self.value == other.value
def __hash__(self):
return hash(self.value)
b = Box(1)
s = {b}
b.value = 2
print(len(s)) # 1, still stored
print(b in s) # False, lookup uses the new hash
print(any(x is b for x in s)) # True, found by scanningThe element is still in the set, but it sits in the slot for hash 1, and the lookup now looks in the slot for hash 2. The object has become effectively lost. Treat any field used by __hash__ as read-only.
How a set decides whether an element is new
Fixing unhashable-element errors
You have three common options, depending on what the data means.
- List to tuple. Convert each list to a tuple. Order is preserved and the elements stay comparable.
- Set to frozenset. Use this when you need a set of sets, and order does not matter.
- Dict to frozenset of items. This works when the dict's values are hashable too.
rows = [[1, 2], [1, 2], [3]]
unique_rows = {tuple(r) for r in rows}
print(sorted(unique_rows)) # [(1, 2), (3,)]
groups = {frozenset({1, 2}), frozenset({2, 1})}
print(len(groups)) # 1
config = {"mode": "fast", "level": 3}
key = frozenset(config.items())
print(key == frozenset({"level": 3, "mode": "fast"}.items())) # TrueIf the nested structure is deeper, convert recursively or serialize it to a string, for example with json.dumps(obj, sort_keys=True). That works only if the data is JSON-compatible.
Hash values are not stable across runs
For str and bytes, Python randomizes the hash on every interpreter start (hash randomization). This makes the iteration order of a set of strings differ between runs. Integer hashes are stable, but you should not rely on order for them either. Never store hash() results on disk or compare them between processes. If you need a stable digest, use hashlib.
Quick checklist
- Can the value change? If yes, convert it to an immutable form before adding it.
- Does it contain a list, dict, or set? Then it is unhashable, even inside a tuple.
- Did you define
__eq__on a class? Define__hash__too, or use@dataclass(frozen=True). - Are you mixing
1,1.0andTrue? They count as the same element.
Exercise
A class defines __eq__ comparing the field name but no __hash__. What happens on {Item("a")}, and what is the smallest correct fix?
Show answer
It raises TypeError: unhashable type: 'Item', because defining __eq__ without __hash__ sets __hash__ to None. Add def __hash__(self): return hash(self.name), using the same field that __eq__ compares, and do not change name after the object is in a set.
Exercise
What does this print, and why? s = {(1, 2), (1.0, 2.0)}; print(len(s))
Show answer
It prints 1. The tuples are equal element by element because 1 == 1.0 and 2 == 2.0, and they have the same hash, so the set treats them as one element.
Exercise
You have data = [{1, 2}, {2, 1}, {3}] and want the unique sets. set(data) raises TypeError. Write the fix and say how many sets remain.
Show answer
unique = {frozenset(x) for x in data} leaves 2 elements, frozenset({1, 2}) and frozenset({3}). Sets are unhashable, but frozensets are, and frozenset({1, 2}) == frozenset({2, 1}).