Junior — Middle
When can a tuple in Python not be used as a key in dictionaries and sets due to hashability?
sobes.tech AI
Answer from AI
A tuple in Python can be used as a dictionary key or set element only if it is hashable. A tuple is hashable itself if all its elements are also hashable. If there are mutable objects inside the tuple, such as lists, dictionaries, or other mutable types, then the tuple will not be hashable and cannot be used as a key in a dictionary or as a set element.
Example:
valid_key = (1, 2, 3) # All elements are hashable
invalid_key = (1, [2, 3]) # List inside the tuple makes it unhashable
d = {}
d[valid_key] = "OK"
# Attempting to use invalid_key will cause an error
# d[invalid_key] = "Error" # TypeError: unhashable type: 'list'