hash() Bulit-in Function
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.
Syntax
The syntax of hash()
function is
hash(object)
where
Parameter | Description |
---|---|
object | Any hashable object. |
An object is hashable if its type has __hash__()
function.
The hash() function returns an integer value.
Examples
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)
print(hashValue)
Output
711200028950563678
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)
print(hashValue)
Output
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.
Related Tutorials
Summary
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.