Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashing arrays in Python

People also ask

What is hashing array?

A hash table uses a hash function to compute an index, also called a hash code, into an array of buckets or slots, from which the desired value can be found. During lookup, the key is hashed and the resulting hash indicates where the corresponding value is stored.

Is there hashing in Python?

Hash method in Python is a module that is used to return the hash value of an object. In programming, the hash method is used to return integer values that are used to compare dictionary keys using a dictionary look up feature.

How hashing is done in Python?

Python hash() methodPython hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer which is used to quickly compare dictionary keys while looking at a dictionary.

Can arrays be hashed?

hashCode(Object[]) method returns a hash code based on the contents of the specified array. If the array contains other arrays as elements, the hash code is based on their identities rather than their contents.


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.


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


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.