Python hash() Function

The hash() function in Python returns the hash value of a specified object. For example:

a = 120
b = "fresherearth"
c = "python programming"
d = True
e = False

print(hash(a))
print(hash(b))
print(hash(c))
print(hash(d))
print(hash(e))

The output will be:

120
1095362836548201503
7646277759735715480
1
0

Note: Hashing in Python, is basically the process of converting any key or a string into another form (value).

Most of the time, hashing is used to represent a value by shorter and fixed-length value that becomes easier to find.

As you can see from above program and its sample output, both the string type object, produces hash value with fixed-length. Similar things goes with both d and e boolean type object.

Note: Since a hash value is basically a fixed-size integer, therefore for int type object, the hash() returns the same value as hash value too.

Python hash() Function Syntax

The syntax of hash() function in Python, is:

hash(obj)

where obj refers to the object whose hash value is to be calculated. Also the obj must be an immutable object.

Python hash() Function Example

The hash value is used to identify a particular value without caring the type of object. For example:

class fresherearth:
    Topic = "Python Programming"

a = fresherearth.Topic
b = "Python Programming"

print(hash(a))
print(hash(b))
print(hash("Python Programming"))

The sample output produced by above program, is shown in the snapshot given below:

python hash function

Important Use of hash in Python

Hash provides a quick look-up of values when dealing with some large collection of values. Set and Dictionary are the two examples. Since in case of a List, if we need to check whether a value is available in the list or not, using:

if x in mylist:

The whole list gets scanned one by one to check whether particular item or element or value is in the list or not. And of course, this may take longer time than usual when dealing with a list having high number of items. But in case of a set, Python keeps track of each hash. So that if we need to check whether an item is available or not using:

if x in myset:

Python will get the value of hash for x, to look that up in the internal structure to only compare x with myset that have same hash as x. This will work much faster than previous method.

Note: Similar things goes in case of dictionary. That is, in case of dictionary, the same things goes with keys of dictionary to look-up for particular key very fast.

It means that, list comes under the category of non-hashable object, unlike set and dict.

Non-hashable objects are objects that is mutable or changeable. That is, if items of an object can be changed, that means the objects comes under the category of non-hashable object.

Whereas hashable objects are objects that is immutable like set, keys of dict.

Python Online Test


« Previous Function Next Function »