Hashable and Not-Hashable types in Python
Python - Hashable and Not-Hashable Types
An object is said to be hashable if hash() function with that object as argument can return an integer (hash value).
In Python, we have primitive datatypes like int, float, str, tuple, dict, list, set, and NoneType. Of these objects of some types are hashable and some are not hashable.
Please refer hash() builtin function for the syntax and usage of hash() function.
Hashable Types
The objects of the following datatypes are hashable in Python.
Non-Hashable Types
The objects of the following datatypes are not hashable in Python.
Note: An observation on the mutability of the hashable and non-hashable types reveal that hashable types are immutable, and non-hashable types are mutable.
Examples
1. Example for hashable types
In the following program, we take objects of hashable types, and print their hash value.
Python Program
obj = 10
print(hash(obj))
obj = 3.14
print(hash(obj))
obj = 'hello world'
print(hash(obj))
obj = tuple([10, 20, 30])
print(hash(obj))
obj = None
print(hash(obj))
Output
10
322818021289917443
3276099033937856553
3952409569436607343
273897708
2. Example for non-hashable types
In the following programs, we take objects of non-hashable types, and try printing their hash value. But, hash() function raises TypeValue error.
Hash value of a dictionary
Python Program
obj = dict({'apple':10, 'banana':20})
print(hash(obj))
Output
Traceback (most recent call last):
File "/Users/pythonexamples/main.py", line 2, in <module>
print(hash(obj))
TypeError: unhashable type: 'dict'
Hash value of a list
Python Program
obj = ['apple', 'banana', 'cherry']
print(hash(obj))
Output
Traceback (most recent call last):
File "/Users/pythonexamples/main.py", line 2, in <module>
print(hash(obj))
TypeError: unhashable type: 'list'
Hash value of a set
Python Program
obj = {'apple', 'banana', 'cherry'}
print(hash(obj))
Output
Traceback (most recent call last):
File "/Users/pythonexamples/main.py", line 2, in <module>
print(hash(obj))
TypeError: unhashable type: 'set'
Summary
In this Python Examples tutorial, we learned what types of objects are hashable and what types are not, with example programs.