Tuple Equality and Hashability
Core idea
Two ordinary tuples compare equal when they contain equal items in the same order and have the same length. A hashable object has a hash value that remains stable during its lifetime, and equal hashable objects must have equal hashes. A tuple is hashable only when every item is hashable. Dictionaries, introduced next, use hashable keys to look up values.
Order matters for tuple equality.
Compare hashes safely
Equal hashable tuples have equal hashes; the exact hash number is not needed.
Intentional error: unhashable member
A list is unhashable, so this tuple is also unhashable.
Common mistake
Different objects can have the same hash. A matching hash alone does not establish equality. Do not rely on exact hash values across interpreter runs or platforms.
Practice
Predict whether (1, (2, 3)), (1, [2, 3]), and () can be dictionary keys. Check each separately with hash().
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Tuple equality and hashability
Check your understanding of tuple equality and hashing.
What is printed?
print((4, 1) == (1, 4))What is printed?
print(hash((2, 8)) == hash((2, 8)))Which error occurs?
hash((1, [2]))Which value can serve as a dictionary key?