In Python, an object is termed “hashable” if it has a hash value that remains constant during its lifetime and can be compared to other objects to check if they’re equal. In simple terms, if an object can be used as a key in a dictionary, then it’s hashable.
The requirement for an object to be used as a dictionary key is that:
- It needs a hash value which never changes.
- It needs to be comparable to other objects.
Most of Python’s immutable built-in objects are hashable:
- int: numbers are hashable because their value never changes.
- float: like numbers, they also have a constant value.
- str: strings are immutable, so they’re hashable.
- tuple: if a tuple contains only hashable elements, it’s hashable.
Mutable built-in objects are typically unhashable:
- list: lists are mutable (you can change their content), so they’re unhashable.
- set: sets are mutable, so they’re unhashable. However, there’s
frozenset
(an immutable version of set) which is hashable. - dict: dictionaries themselves are mutable and hence unhashable, but their keys must be hashable.
Simple Example:
Imagine you want to use a dictionary to store the favorite color of different fruits.
# This works because strings are hashable
favorite_colors = {
"apple": "red",
"banana": "yellow",
"grape": "purple"
}
# This doesn't work because lists are unhashable
# favorite_colors_list = {
# ["apple"]: "red", # Raises a TypeError
# ["banana"]: "yellow",
# ["grape"]: "purple"
# }
# This does work because tuple are hashable -------------------------
# favorite_colors_list = {
# ("apple",): "red",
# ("banana"): "yellow",
# ("grape"): "purple"
# }
Tuples containing mutable elements can lead to unexpected bugs. In the context of ‘What Is Hashable’, an object is deemed hashable only if its value remains constant. Consequently, tuples that are unhashable cannot serve as dictionary keys or set members.
If you wish to explicitly check whether a tuple (or any other object) possesses a constant value, you can employ the built-in hash
function to craft such a determinative method as follows:
def is_hashable(obj):
"""Return True if the object is hashable (immutable), False otherwise."""
try:
hash(obj)
except TypeError:
return False
return True
# Test cases
tf = (10, 'alpha', (1, 2))
tm = (10, 'alpha', [1, 2])
print(is_hashable(tf)) # Outputs: True
print(is_hashable(tm)) # Outputs: False
eos qui deserunt omnis beatae aut non consequatur ullam non qui est repellendus accusantium dignissimos nemo possimus quas ea dolore quas repellendus. non molestias voluptate sit vero sed corporis eaq
eligendi aut qui aut id corrupti doloribus architecto. quidem rerum quibusdam eaque temporibus eaque molestiae sed voluptatem nemo.
sed quae eos at incidunt mollitia voluptas et hic veniam magni delectus est sapiente eaque. expedita fugit mollitia dolore sint veritatis eaque eaque dolorum adipisci sed quam.