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, as 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 aren’t hashable because changing their content would alter their hash value and violate the requirement for it to be constant.
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 not hashable objects in Python:
>>> # Hashable
>>> hash(42)
42
>>> hash("Real Python")
3074007028937194714
>>> numbers = (1, 2, 3)
>>> hash(numbers)
529344067295497451
>>> # Not hashable
>>> 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 chaining their content will affect the hash value.
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: