[Tutor] how to understand unhashable type: 'list'

Peter Otten __peter__ at web.de
Thu Nov 17 20:03:03 CET 2011


Steven D'Aprano wrote:

> Immutable objects are those that cannot be changed in place: you have to
> create a new object. Tuples, frozensets, strings, ints, floats are all
> immutable. They are hashable.

Tuples are special: there are hashable and unhashable tuples. To be hashable 
all items in a tuple have to be hashable:

>>> a = 1, 2
>>> hash(a)
3713081631934410656
>>> b = 1, []
>>> hash(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Instances of custom classes are special, too; by default they are hashable 
and mutable. That is possible without messing things up too much because 
instead of the instance's data they use its id() to calculate the hash value 
(and object equality). This is obvious in older Python versions like

Python 2.6.4 (r264:75706, Dec  7 2009, 18:43:55)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A: pass
...
>>> a = A()
>>> id(a)
140312106243352
>>> hash(a)
140312106243352
>>> id(a) == hash(a)
True

but the principle also applies in 2.7 and 3.1 and above.



More information about the Tutor mailing list