A tuple is immutable as a container, but hashing it requires every contained value to be hashable.
Python interview: a tuple can be unhashable when it contains a list
Operation contract
The receipt key holds a route and a list of identifiers. The tuple cannot swap fields, yet the list can change, so using the tuple as a dictionary key raises TypeError. Converting the identifiers to a tuple gives a hashable key for these string elements. The accepted key is then used for one lookup.
Failure and ownership boundary
Calling tuple() is only a shallow conversion. A tuple containing another unhashable element still fails, and a custom hashable object with mutable equality state can corrupt mapping lookup expectations. Python hash and equality: immutable dictionary keys, Python interview: mutating a hash key breaks dictionary lookup assumptions and Python tuples: immutable containers can still contain mutable state are the next checks.
Working program
receipt_ids = ["R41", "R42"]
rejected_key = ("north", receipt_ids)
try:
{rejected_key: 2}
except TypeError:
print("mutable member rejected")
accepted_key = ("north", tuple(receipt_ids))
counts = {accepted_key: 2}
print(counts[("north", ("R41", "R42"))])Output
mutable member rejected
2Costs and limits
For k identifiers, creating the nested tuple and hashing it cost O(k) work on first use. The mapping retains the tuple and its referenced immutable strings.
Common Mistakes
- Tuple immutability does not make every member hashable.
- A shallow tuple conversion does not freeze nested objects.
Connected lessons
Python hash and equality: immutable dictionary keys, Python interview: mutating a hash key breaks dictionary lookup assumptions, Python tuples: immutable containers can still contain mutable state.
