Tutorial Study Image

Python hash()

In python, the built-in function hash()is used to obtain the hash value of the given object. To compare dictionary keys while a dictionary lookup these integer hash values are used. Actually the hash() method calls __hash__() method of an object.

Hashable types: * bool * int * long * float * string * Unicode * tuple * code object

Non-hashable types: * bytearray * list * set * dictionary * memoryview


hash(object) #Where object can be integer, string, float etc.

hash() Parameters: 

Takes a single parameter. Numeric values which are equal will have the same hash value irrespective of their data types.

Parameter Description Required / Optional
object the object whose hash value is to be returned (integer, string, float) Optional

hash() Return Value

hash() method returns the hash value of an object if it has one. The object with custom __hash__() method, it truncates the return value to the size of Py_ssize_t.

Input Return Value
object Hash value

Examples of hash() method in Python

Example 1: How hash() works in Python?


# hash for integer unchanged
print('Hash for 181 is:', hash(181))

# hash for decimal
print('Hash for 181.23 is:',hash(181.23))

# hash for string
print('Hash for Python is:', hash('Python'))
 

Output:

Hash for 181 is: 181
Hash for 181.23 is: 530343892119126197
Hash for Python is: 2230730083538390373 

Example 2: hash() for immutable tuple object?


# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')

print('The hash is:', hash(vowels))

Output:


The hash is: -695778075465126279

Example 3: hash() for Custom Objects by overriding __hash__()



class Person:
    def __init__(self, age, name):
        self.age = age
        self.name = name

    def __eq__(self, other):
        return self.age == other.age and self.name == other.name

    def __hash__(self):
        print('The hash is:')
        return hash((self.age, self.name))
 pers 'Adam')
print(hash(person))
 

Output:


The hash is:
3785419240612877014