In this article we’ll go through the Python hash function and it’s uses, complete with several examples.
Most objects in python have a “hash” number. The
hash() function returns this hash value when it is applied to one of these objects. Objects with the
__hash__() are the ones that have a hash value. Any easy way to check if a object has this method is to use the help() function on it. Doing so will reveal all it’s methods among-st other things.
The hash function comes with a limitation or two on the type of objects passed through it and some other quirks.
- The hash function only works on immutable objects. This automatically rules out objects like lists and dictionaries.
- Same numerical values have the same hash value. For instance,
6.0have the same hash.
- hash Function takes only one parameter at a time.
Hashable and Non Hashable
>>> hash(1) 1 >>> hash(1.00) 1 >>> hash((1,3,7)) 2528501712791978082 >>> hash('Hello World') -2864993036154377761 >>> hash(True) 1 >>> hash([1,2,4,6]) Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> hash([1,2,4,6]) TypeError: unhashable type: 'list'
As we mentioned earlier, lists cannot be hashed. Hence we tried, a
TypeError exception was thrown.
This marks the end of the Python hash Function. Any suggestions or contributions for CodersLegacy are more than welcome. Questions can be asked in the comment section below.
Here’s a link back to the main Python Built-in Functions page.