Python hash() Function

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.


Syntax

hash(object)

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 and 6.0 have the same hash.
  • hash Function takes only one parameter at a time.

Hashable and Non Hashable

HashableNon-Hashable
boollists
stringdictionaries
intsets
floatbytearray
long
tuple
Unicode

Examples

>>> 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.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments