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

Python Built-in Function hash:

The Hash values are integers that are used to uniquely identify the objects, for example, a Python dict is used to compare the keys during a dictionary lookup.

If the object is not hashable, then the hash() function raises a TypeError exception.

Signature

The signature for the hash() function is as shown below.

hash(object)

Parameters and return type

  • This function takes an object which we need to convert into a hash.
  • However, it returns the hash value if available.

Python Built-in Function hash Examples:

Example 1:  For this example, we will take an integer number and print its hash value.

#Initializing
a = 10

#Using hash and Printing
result = hash(a)
print('Hash Value -', result)

Output

Hash Value - 10

Example 2: In this case, we will demonstrate a hash function with a string parameter. Here, for every execution, it will print different hash values.

#Initializing
a = "python"

#Using hash and Printing
result = hash(a)
print('Hash Value -', result)

Output

Hash Value - 6695277865987588527

Example 3: For this example, let us take a list and a tuple containing numbers. Since a tuple is a hashable object it will print its hash value. Whereas, the list is not hashable, so it will raise an exception.

#Initializing
a = [1,2,3]
b=(1,2,3)

#Using hash and Printing
result = hash(b)
print('Hash Value :', result)
result = hash(a)
print('Hash Value :', result)

Output

Hash Value : 529344067295497451
Traceback (most recent call last):
  File "main.py", line 5, in 
    result = hash(a)
TypeError: unhashable type: 'list'

Conclusion

Hence, the hash() function returns a hash value for an object, if available. Otherwise, it will raise an exception.

References

Happy Learning 🙂