Hash in Python

Hash in Python

Last updated on 21st Sep 2020, Artciles, Blog

About author

Vikram ( (Sr Project Manager ) )

He is Highly Experienced in Respective Technical Domain with 6+ Years, Also He is a Respective Technical Trainer for Past 5 Years & Share's This Important Articles For us.

(5.0) | 14677 Ratings 442
  • The hash() method returns the hash value of an object if it has one.
  • Hash values are just integers that are used to compare dictionary keys during a dictionary lookup quickly.
  • Internally, the hash() method calls __hash__() method of an object which is set by default for any object. We’ll look at this later.

What is Python Hash?

  • Python is a high-level programming language that comes with a variety of built-in libraries which comprises many functions and modules. Hash in Python is one such module. 
  • Hash is used to return the hash value of any object. In a programming language, the hash is used to return integer values, which are actually utilized in comparing dictionary keys with the help of the dictionary lookup. 
  • It calls for _hash_() of an object. While using the hash method the following syntax must be used: hash (object)
Subscribe For Free Demo

Error: Contact form not found.

Hashing

It is a process where the algorithm is used for mapping data to a fixed-length where data can be of any size.  This is known as a hash value. It is used to produce high performance and direct access to data structures. This enables the storage of a large amount of data that can be accessed quickly and easily.

hash() Syntax

The syntax of hash() method is:

hash(object)

hash() Parameters

hash() method takes a single parameter:

  • object – the object whose hash value is to be returned (integer, string, float)

Return value from hash()

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

Examples

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

2. Hash() for an immutable tuple object?

  • hash() method only works for immutable objects as tuple.

    # tuple of vowels

    vowels = (‘a’, ‘e’, ‘i’, ‘o’, ‘u’)

    print(‘The hash is:’, hash(vowels))

Output

The hash is: -695778075465126279

3. How hash() works for custom objects?

As stated above, hash() method internally calls __hash__() method. So, any objects can override __hash__() for custom hash values.

But for correct hash implementation, __hash__() should always return an integer. And, both __eq__() and __hash__() methods have to be implemented.

  • 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))

    person = Person(23, ‘Adam’)

    print(hash(person))

Output

The hash is:

3785419240612877014

Note: You don’t have to implement __eq__() method for the hash as it is created by default for all objects

The above example describes how to override both _eq_() and _hash_() and compare your own custom objects.

You can refer the below table to understand how to implement custom hash values:

_eq_()_hash_()Description
If mutable objects are definedDon’t defineHash key value must be immutable
If defined by defaultDefined by defaultAll objects will be compared as unequal
Not definedDon’t defineIn case _eq_() is not defined, then there is no need to define hash as well
DefinedNot defined_hash_() will automatically get adjusted to none and TypeError will be raised
DefinedDo not wish to hash_hash_= None
TypeError will be raised
DefinedRetain from Parent_hash_ = ._hash_
Python Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

Why mutable objects cannot be Hashed?

The restriction on mutable objects actually simplifies the hash table in huge terms. If in case, mutable objects were permitted for hashing, then the hash table must be updated every single time when the value of an object is updated. 

 In Python, there are only two objects which use hash tables that are dictionaries and sets.

  • A dictionary is known as an associative array. Only the keys can be hashed in a dictionary and the values cannot be hashed. Hence, a dictionary key must always be an immutable object and the while values can remain anything.
  • A set consists of unique objects that can be hashed. If there are non-hashable objects in a set, you cannot use a set and instead you must consider using a list.

Are you looking training with Right Jobs?

Contact Us

Popular Courses