hash() Function in Python

Python hash() Function

In Python, the hash() function is a built-in function that returns the hash value of an object. The hash value is an integer that represents the object and is used for various purposes, such as dictionary keys or set membership tests.

The hash() function takes an object as its argument and returns the hash value. It has the following syntax:

hash(object)

Here, object is the object for which you want to calculate the hash value. The object can be of any type, such as integers, strings, tuples, or custom objects.

It's important to note that not all objects can be hashed. Immutable objects, such as numbers, strings, and tuples, can be hashed because their values cannot be changed after they are created. Mutable objects, such as lists and dictionaries, cannot be hashed because their values can change, and therefore, their hash values would also change.

Let's look at some examples to see how the hash() function works:

print(hash(42))             # Output: 42
print(hash('Hello'))        # Output: -8742895781386198007
print(hash((1, 2, 3)))      # Output: 529344067295497451

In these examples, the hash() function returns the hash value for the respective objects. The hash value for integers and tuples is the same as their numerical value, while the hash value for strings is a large integer calculated based on the string's contents.

Keep in mind that the hash value is not guaranteed to be unique for different objects. In rare cases, different objects may have the same hash value (known as hash collisions), although the built-in types in Python are designed to minimize the likelihood of collisions.

Lastly, it's worth mentioning that the hash() function requires the object to be hashable. If you try to hash an object that is not hashable, such as a mutable object like a list, you will encounter a TypeError.