Hashing arrays in Python

xlharambe picture xlharambe · Aug 11, 2011 · Viewed 88.7k times · Source

Is it possible to hash lists?

For example, I know that hashes of tuples are possible:

>>> hash((1,2,3,4,5,6))
-319527650

But is it possible to hash a list?

>>> hash([1,2,3,4,5,6])
hash_value

Possible Solution:

Very in depth explanation to the hashing of lists, here.

Answer

Roman Bodnarchuk picture Roman Bodnarchuk · Aug 11, 2011

Just try it:

>>> hash((1,2,3))
2528502973977326415
>>> hash([1,2,3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(frozenset((1,2,3)))
-7699079583225461316
>>> hash(set((1,2,3)))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'

So you can get hash of tuple and frozenset since the are immutable, and you can't do it for list and set because they are mutable.