hashable
In Python, an object is considered hashable if it has a hash value that remains constant during the object’s lifetime.
Hashable objects can be used as a key in a dictionary or as an element in a set, since both data structures rely on hashing to efficiently look up and store elements.
To be hashable, an object must implement the .__hash__() method and the .__eq__() method. Immutable built-in types like integers, strings, and tuples containing only hashable elements are hashable. Mutable types like lists and dictionaries have .__hash__() set to None by design, making them unhashable. This prevents silent data corruption that would occur if a key’s hash changed after insertion into a dictionary or set.
Example
To find the hash value of an object and determine whether it’s hashable, you can use the built-in hash() function. Here are examples of hashable and non-hashable objects in Python:
>>> # Hashable
>>> hash(42)
42
>>> hash("Real Python")
3074007028937194714 # Varies per session
>>> numbers = (1, 2, 3)
>>> hash(numbers)
529344067295497451 # Varies per session
>>> # Not hashable
>>> hash([1, 2, 3])
Traceback (most recent call last):
...
TypeError: unhashable type: 'list'
>>> hash((1, [2, 3]))
Traceback (most recent call last):
...
TypeError: unhashable type: 'list'
Numbers and strings are hashable. Tuples are only hashable if all their items are hashable. Lists aren’t hashable because they have .__hash__() set to None.
Related Resources
Tutorial
Build a Hash Table in Python With TDD
In this step-by-step tutorial, you'll implement the classic hash table data structure using Python. Along the way, you'll learn how to cope with various challenges such as hash code collisions while practicing test-driven development (TDD).
For additional information on related topics, take a look at the following resources: