#Use the hash function



The hash() function is used to return the hash value of an object.

obj The object whose hash value we want.

A hash value is a unique identifier or numeric representation associated with an object. It is calculated based on the object's content or characteristics.

print(hash('Hello, World!'))

Hashable and Unhashable objects

An object is hashable if it has a hash value which never changes during its lifetime and is usable as a key in a dictionary. Typically all immutable objects such as strings, tuples, integers, floats e.tc are hashable. On the other hand, objects which are mutable are generally not hashable, for example, list, set, and dictionary. calling unhashable object with the hash function will raise an error.

hash([1, 2, 3])

more hash examples:

hash('Hello, World!')
hash((1, 2, 3))

The hash() function is designed to have an extremely strong guarantee of uniqueness. That means that two objects with the same value will always have the same hash value. However, hash value associated with some value will vary across runs. This means that the value returned at one session, may and will most likely be different when you close and call the interpreter again. There are exceptions, for example a given integer always have a hash value equal to it's value. 

with user defined objects

We can make a user-defined object hashable by defining the __hash__ method. 

class Example:
     def __init__(self, name):
         self.name = name
     def __hash__(self):
          return hash(self.name)
e = Example('example instance')