The hash()
function is used to return the hash value of an object.
hash(obj)
copy
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.
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.
more hash examples:
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.