0
0
PythonConceptBeginner · 3 min read

What Is Hashable in Python: Explanation and Examples

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

python
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}")
Output
Error: unhashable type: 'list'
🎯

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, and tuple are hashable.
  • Mutable types like list and dict are not hashable.
  • Hashable objects can be used as dictionary keys or set elements.

Key Takeaways

Hashable objects have a constant hash value and can be used as dictionary keys or set elements.
Immutable types like strings and tuples are hashable, while mutable types like lists are not.
Trying to use an unhashable object as a dictionary key raises a TypeError.
Use hashable objects when you need fast lookups in dictionaries or sets.