1.

Explain hash() function in the built-in library.

Answer»

The hash() functions hash value of given object. The object MUST be immutable. Hash value is an integer specific to the object. These hash values are used during DICTIONARY LOOKUP

Two objects may hash to the same hash value. This is CALLED Hash collision. This means that if two objects have the same hash code, they do not necessarily have the same value.

>>> #hash of a number >>> hash(100) 100 >>> hash(100.00) 100 >>> hash(1E2) 100 >>> hash(100+0j) 100

You can see that hash value of an object of same numeric value is the same.

>>> #hash of string >>> hash("hello") -1081986780589020980 >>> #hash of tuple >>> hash((1,2,3)) 2528502973977326415 >>> #hash of list >>> hash([1,2,3]) Traceback (most RECENT call last):   File "<pyshell#23>", line 1, in <module>     hash([1,2,3]) TypeError: unhashable type: 'list'

Last case of hash value of list results in TypeError as list is not immutable /not hashable.

The hash() function internally calls __hash__() magic method. To obtain a hash value of object of user defined class, the class itself should provide overridden implementation of __hash__()

class User:     def __init__(self, age, name):         self.age = age         self.name = name     def __hash__(self):         return hash((self.age, self.name)) x = User(23, 'Shubham') print("The hash is: %d" % hash(x))

Output:

The hash is: -1916965497958416005


Discussion

No Comment Found