Python hash() Method

The hash() method returns the hash value of the specified object. The hash values are used in data storage and to access data in a short time per retrieval, and storage space only fractionally greater than the total space required for the data or records themselves. In Python, has values are used to compare dictionary keys to access values.

Syntax:

hash(object)

Parameters:

object: Required. The object (int, string, float) whose hash value is to be returned.

Return type:

Return an integer (The hash value of the object)

The following example demonstrates the hash() method.

Example: Get Hash Values
print("The hash value of 200 is: ", hash(200))
print("The hash value of 200.01 is: ", hash(200.01))
print("The hash value of programming is: ", hash("programming"))
print("The hash value for a tuple is: ", hash((1,2,3,4,5)))
Output
The hash value of 200 is:  200
The hash value of 200.01 is:  23058430092116168
The hash value of programming is:  -857083564838631708
The hash value for a tuple is:  8315274433719620810

If an object is passed as an arguement is not hashable e.g. a list object, then the TypeError exception is thrown.

Example: hash()
print(hash([1,2,3,4])
Output
Traceback (most recent call last):
    print(hash([1,2,3,4]))
TypeError: unhashable type: 'list'
Want to check how much you know Python?