Python hash() Function



The Python hash() function is used to return the hash value of an object, if it is hashable. The Hash values are of integer type used for comparing dictionary keys during a dictionary lookup.

Note that only the immutable objects are hashable. This means that objects whose value cannot change over time, such as tuples, strings, and integers, can be hashed. The reason is that if an object's value can change, its hash value can also change.

In the next few section, we will be learning more about this function.

Syntax

Following is the syntax of the python hash() function.

hash(object)  

Parameters

The python hash() function accepts a single parameter −

  • object − This parameter specifies an object for which we want hash value.

Return Value

The python hash() function returns hash value of the specified object.

Examples

Now, let's see how hash() function works with the help of some examples −

Example 1

The following is an example of the python hash() function. In this, we have defined a float and an integer value and, trying to find the hash value of both values.

intNums = 56
output1 = hash(intNums)
floatNums = 56.2
output2 = hash(floatNums)
print(f"The hash for {intNums} is: {output1}")
print(f"The hash for {floatNums} is: {output2}")

On executing the above program, the following output is generated −

The hash for 56 is: 56
The hash for 56.2 is: 461168601842745400

Example 2

Strings are also hashable, if we pass a string as an argument to the hash() function, then, it will return its hash value.

varStr = "Tutorialspoint"
output = hash(varStr)
print(f"The hash for '{varStr}' is: {output}")

The following is the output obtained by executing the above program −

The hash for 'Tutorialspoint' is: 887219717132446054

Example 3

In the following example, we are applying hash() function on the custom object. Here, we will assign a hash value to the object by using constructor of the class.

class NewClass:
   def __init__(self, value):
      self.value = value
   def __hash__(self):
      return hash(self.value)

newObj = NewClass(10)
output = hash(newObj)
print(f"The hash for given object is: {output}")

The following output is obtained by executing the above program -

The hash for given object is: 10

Example 4

In this example, we are demonstrating how to find the hash value of a tuple. For this operation, we simply need to pass the tuple name to the hash() function as an argument.

numsTupl = (55, 44, 33, 22, 11)
output = hash(numsTupl)
print(f"The hash for given list is: {output}")

The above program, on executing, displays the following output -

The hash for given list is: -6646844932942990143
python_built_in_functions.htm
Advertisements