Hashable vs Unhashable in Python: Key Differences and Usage
hashable objects have a fixed hash value and can be used as dictionary keys or set elements, while unhashable objects do not have a fixed hash and cannot be used in these contexts. Typically, immutable types like int, str, and tuple are hashable, whereas mutable types like list and dict are unhashable.Quick Comparison
Here is a quick side-by-side comparison of hashable and unhashable objects in Python.
| Aspect | Hashable | Unhashable |
|---|---|---|
| Definition | Has a fixed hash value | Does not have a fixed hash value |
| Can be dictionary keys? | Yes | No |
| Can be set elements? | Yes | No |
| Typical types | int, str, tuple | list, dict, set |
| Mutability | Immutable | Mutable |
| Example usage | Used as keys in dicts or elements in sets | Cannot be used as keys or set elements |
Key Differences
Hashable objects in Python have a hash value that does not change during their lifetime. This property allows them to be used as keys in dictionaries or as elements in sets, which rely on hashing for fast lookup. Immutable built-in types like int, str, and tuple are hashable because their content cannot change.
On the other hand, unhashable objects either do not implement a __hash__() method or have a mutable state that can change, making their hash value unreliable. Mutable types like list, dict, and set are unhashable to prevent errors in hash-based collections.
Trying to use an unhashable object as a dictionary key or set element raises a TypeError. This distinction ensures data integrity and consistent behavior in Python's hash-based data structures.
Code Comparison
Here is an example showing how a hashable object can be used as a dictionary key.
my_dict = {}
key = (1, 2, 3) # tuple is hashable
my_dict[key] = "value"
print(my_dict[key])Unhashable Equivalent
Trying to use an unhashable object like a list as a dictionary key will cause an error.
my_dict = {}
key = [1, 2, 3] # list is unhashable
try:
my_dict[key] = "value"
except TypeError as e:
print(f"Error: {e}")When to Use Which
Choose hashable objects when you need to use items as keys in dictionaries or elements in sets for fast lookup and uniqueness. Use immutable types like int, str, or tuple for this purpose.
Use unhashable objects when you need mutable collections that can change over time, like lists or dictionaries themselves. These are not suitable as keys but are useful for storing and modifying data.