Hashing arrays in Python

PythonArraysHash

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

If you really need to use a list as a dictionary key, try converting it to a string first.
my_list = str(my_list)

Solution 3 - Python

Python doesn't allow you to use mutable data as keys in dictionaries, because changes after insertion would make the object un-findable. You can use tuples as keys.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1786283View Question on Stackoverflow
Solution 1 - PythonRoman BodnarchukView Answer on Stackoverflow
Solution 2 - PythonOhmlessView Answer on Stackoverflow
Solution 3 - PythonNed BatchelderView Answer on Stackoverflow