Python hash() Function
Hello everyone, in this tutorial we are going to see how the Python hash() function works and how we can use it in our program.
Python hash() Function: Syntax and Properties
The syntax for the python hash() function is as given here.
The hash() function takes an object as a parameter and returns the hash value of that object if it exists. This function internally makes a call to _hash_() method to get the hash value of the object.
What are hash values?
In python, every object is encoded with an integer called hash value. Here are some key points about hash values.
- In python, hash values are assigned according to the value of the object. Therefore, if two objects have the same value, their hash value also would be the same. See the code.
str1 = "what's up" print(hash(str1)) str2 = "what's up" print(hash(str2)) print(hash("what's up"))
Running the code gives the following output:
-3623925955062450651 -3623925955062450651 -3623925955062450651
As you can see in the above code we have defined two string objects with the same values, it produces the same hash value for both.
- Hash values can be different for the different run of the program. If we run the above code again our output will be somewhat like this.
141968900690448161 141968900690448161 141968900690448161
As you can see the hash values are different than the values obtained in the previous execution.
- hash() function returns hash values only for immutable objects. For objects like list, set, dictionary, etc it throws TypeError. That’s why we call these objects non-hashable in python. See the given code.
tuple1 = (1,2,3) print(hash(tuple1)) list1 = [1,2,3] print(hash(list1))
Running the above code gives the following output.
2528502973977326415 Traceback (most recent call last): File "hash.py", line 5, in <module> print(hash(list1)) TypeError: unhashable type: 'list'
As you can see, the program prints the hash value for the tuple1 object which is immutable and throws a TypeError for list1 object which is mutable. We can use this property of hash() function to distinguish between mutable and immutable objects in python.
Also, read: Python id() function