hash() Bulit-in Function

Python – hash()

Python hash() built-in function returns the hash value of a given object.

Hash values are integer numbers.

Where are hash values used?

Hash values are used during comparison.

For example, during a dictionary lookup, a comparison has to be made between the given key and the dictionary keys. If keys are strings, it might take lot of CPU resources for comparing two strings. But if hash values of the keys, which are integers, are used for comparison, then the performance is greatly improved.


The syntax of hash() function is



  • object is any hashable object.

An object is hashable if its type has __hash__() function.

The hash() function returns an integer value.


1. Get the hash value of a string

In the following program, we take a string value in obj, get its hash value using the hash() function, and print the hash value to output.

Python Program

obj = 'hello world'
hashValue = hash(obj)



2. List is not hashable

In the following program, we take a list in obj and try to get its hash value using the hash() function. Since the list is not a hashable type, the hash() function throws TypeError.

Python Program

obj = [5, 10, 14, 0, 84]
hashValue = hash(obj)


Traceback (most recent call last):
  File "/Users/arjun/Desktop/flask_app/main.py", line 2, in <module>
    hashValue = hash(obj)
TypeError: unhashable type: 'list'

Related Tutorials


In this Built-in Functions tutorial, we learned the syntax of the hash() built-in function, and how to use this function to get the hash value of an object, with examples.