Python hash()

Python hash() builtin function is used to get the hash value of the given object, if it has any.

If the object is unhashable, then hash() function raises TypeError.

Hash value may change from run to run, for non-integer objects.

In this tutorial, we will learn about the syntax of Python hash() function, and learn how to use this function with the help of examples.

Syntax

The syntax of hash() function is

hash(object)

where object is a Python object.

Returns

The function returns an int value.

ADVERTISEMENT

Examples

1. Hash Value of a String Object

In this example, we take a string object in variable a, and find its hash value. We print the hash value and the type of hash value.

Python Program

a = 'hello world'
result = hash(a)
print('Hash Value :', result)
print(type(result))
Try Online

Output

Hash Value : 1661037396842413954
<class 'int'>

2. Hash Value of a Int Object

In this example, we take an integer object in variable a, and find its hash value. We print the hash value of this object to console.

Python Program

a = 125
result = hash(a)
print('Hash Value :', result)
Try Online

Output

Hash Value : 125

3. Hash Value of a List Object

In this example, we take a List object in variable a, and try to find its hash value.

Python Program

a = [1, 5, 4]
result = hash(a)
print(result)
Try Online

Output

TypeError: unhashable type: 'list'

Since list is not a hashable type, hash() raises TypeError.

Conclusion

In this Python Tutorial, we have learnt the syntax of Python hash() builtin function, and also learned how to use this function, with the help of Python example programs.