0
0
PythonComparisonBeginner · 4 min read

Hashable vs Unhashable in Python: Key Differences and Usage

In Python, 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.

AspectHashableUnhashable
DefinitionHas a fixed hash valueDoes not have a fixed hash value
Can be dictionary keys?YesNo
Can be set elements?YesNo
Typical typesint, str, tuplelist, dict, set
MutabilityImmutableMutable
Example usageUsed as keys in dicts or elements in setsCannot 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.

python
my_dict = {}
key = (1, 2, 3)  # tuple is hashable
my_dict[key] = "value"
print(my_dict[key])
Output
value
↔️

Unhashable Equivalent

Trying to use an unhashable object like a list as a dictionary key will cause an error.

python
my_dict = {}
key = [1, 2, 3]  # list is unhashable
try:
    my_dict[key] = "value"
except TypeError as e:
    print(f"Error: {e}")
Output
Error: unhashable type: 'list'
🎯

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.

Key Takeaways

Hashable objects have a fixed hash and can be dictionary keys or set elements.
Unhashable objects are mutable and cannot be used as keys or set elements.
Immutable types like tuples are hashable; mutable types like lists are not.
Using unhashable objects as keys raises a TypeError.
Choose hashable types for fast lookup and unhashable types for mutable data.