Python – hash()
Python hash() built-in function returns the hash value of a given object. The hash value of an object is an integer.
In this tutorial, you will learn the syntax of hash() function, and then its usage with the help of example programs.
The syntax of hash() function is
|object||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.
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.
Traceback (most recent call last): File "/Users/arjun/Desktop/flask_app/main.py", line 2, in <module> hashValue = hash(obj) TypeError: unhashable type: 'list'
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.
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.