Published on

Why list / dict objects are unhashable in python?

Authors
  • avatar
    Name
    Gene Zhang
    Twitter
d = {
    []: "list"
}
TypeError: unhashable type: 'list'

d = {
    {}: "dict"
}
TypeError: unhashable type: 'dict'

Short answer: because they are mutable containers.

If a dict was hashed, its hash would change as you changed its contents.

https://stackoverflow.com/a/1957403/21196822

What does “hashable” mean in Python?

From the Python glossary:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dict) are.

Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().