Python hash() is a built-in function that returns the hash value of an object ( if it has one ). Hash values are integers used to quickly compare dictionary keys while looking up a dictionary.

python hash() function

Behind the scenes Python hash() function calls, __hash__() method internally to operate on different types of data types. __hash__() method is set by default for any object.

Python hash() Syntax

hash(object)

hash() function takes only one parameter.

  • object (required) – The object whose hash value is to be returned. Only immutable objects can be hashed.

Note: Numeric values which are equal will have same has value irrespective of their data types. For example, 2 and 2.0 have same hash value.

For the objects having custom __hash__() method, the hash() function trucates the return value as per the bit width of machine i.e to the size of Py_ssize_t.

List of hashable and non-hashable Python data types

  • Hashable – bool, int, long, float, string, unicode, tuple
  • NonHashablelists, set, dictionary, bytearray

Python hash() Example

>>> hash(2)
2

>>> hash(2.00)
2

>>> hash('Python')
397710083

>>> hash(5+5j)
5000020

>>> #using hash function for tuple
>>> hash((1,2,3,4))
89902565

>>> #using hash function for list
>>> hash([1,2,3,4])
Traceback (most recent call last):
 File "<pyshell#11>", line 1, in <module>
 hash([1,2,3,4])
TypeError: unhashable type: 'list'

>>> #using hash function for set
>>> hash({1,2,3,4})
Traceback (most recent call last):
 File "<pyshell#12>", line 1, in <module>
 hash({1,2,3,4})
TypeError: unhashable type: 'set'

As you can see in above example, hash() function returns hashed value for hashable data types (tupes/integers), whereas it throws TypeError for unhashable data types (set/list/dicionary etc).