What Is Hashable in Python: Explanation and Examples
hashable if it has a fixed hash value during its lifetime and can be compared to other objects. Hashable objects can be used as keys in dictionaries or stored in sets because their hash value helps Python quickly find them.How It Works
Think of hashable objects like labeled boxes with a unique ID that never changes. This ID is called a hash. Python uses this ID to quickly find the box without opening every box one by one.
For an object to be hashable, its content must not change over time. If the content changes, the ID would change, and Python would get confused about where to find it. That's why mutable objects like lists are not hashable, but immutable objects like strings and tuples are.
Example
This example shows which objects are hashable and which are not by trying to use them as dictionary keys.
my_dict = {}
# Strings are hashable
my_dict["apple"] = 1
# Tuples are hashable if they contain only hashable items
my_dict[(1, 2)] = 2
# Lists are not hashable and will raise an error
try:
my_dict[[1, 2, 3]] = 3
except TypeError as e:
print(f"Error: {e}")When to Use
Use hashable objects when you need to store data in sets or as keys in dictionaries. These data structures rely on hash values to quickly find, add, or remove items.
For example, if you want to count how many times each word appears in a text, you can use a dictionary with words as keys. Since strings are hashable, this works perfectly.
Key Points
- Hashable objects have a fixed hash value that does not change during their lifetime.
- Immutable built-in types like
int,str, andtupleare hashable. - Mutable types like
listanddictare not hashable. - Hashable objects can be used as dictionary keys or set elements.