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.
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.
hash(object)
hash()
function takes only one parameter.
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
.
>>> 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).