This guide explains understand hashability with simple examples through a focused Python example. You will learn the behavior to expect, why it matters in a real program, and how to recognize the common mistakes before applying it in your own project.
What You Will Learn
A hashable object has a hash value suitable for dictionary keys and set members, and its equality/hash behavior must stay consistent during its lifetime. Integers, strings and suitable tuples are commonly hashable; lists and dictionaries are not.
When and Why to Use It
The following example focuses on a practical use of Understand Hashability with Simple Examples.
Step-by-Step Example
valid_keys = {(2026, "October"): "report", "status": "ready"}
print(valid_keys[(2026, "October")])
try:
invalid_keys = {["draft", "review"]: 1}
except TypeError as error:
print(type(error).__name__)
Understanding the Example
A tuple containing immutable, hashable elements works as a dictionary key. A list cannot be hashed, so attempting to use it as a key raises TypeError.
Expected Output
report
TypeError
Important Behavior and Edge Cases
A tuple is not automatically hashable: a tuple containing a list is unhashable, too. Hashability is not simply the same as being read-only.
Try It Yourself
Test hash((1, 2)) and then test hash((1, [2])) inside a try block.
Common Beginner Mistakes
- A tuple is not automatically hashable: a tuple containing a list is unhashable, too. Hashability is not simply the same as being read-only.
- Using the wrong collection type can silently discard ordering or confuse lookup with membership testing.
- Skipping the practice step and assuming the example covers every input. Test at least one normal case and one edge case relevant to this topic.
Key Takeaways
- A hashable object has a hash value suitable for dictionary keys and set members, and its equality/hash behavior must stay consistent during its lifetime.
- A tuple containing immutable, hashable elements works as a dictionary key.
- Apply the technique deliberately, checking its documented input requirements and failure behavior before integrating it into a larger project.