Why Are Tuples Hashable but Lists Are Not in Python?
tuples are hashable because they are immutable, meaning their content cannot change after creation. Lists are not hashable because they are mutable and can be changed, which would break the consistency needed for hashing.How It Works
Hashing is like giving an object a unique ID based on its content. This ID helps Python quickly check if two objects are the same when using them as keys in dictionaries or elements in sets.
Tuples are immutable, which means once you create a tuple, you cannot change its content. This stability allows Python to calculate a fixed hash value for the tuple that never changes.
Lists, on the other hand, can be changed after creation — you can add, remove, or modify items. Because their content can change, their hash value would also have to change, which is not allowed. So, Python makes lists unhashable to avoid errors and confusion.
Example
This example shows that tuples can be used as dictionary keys because they are hashable, but lists cannot.
my_dict = {}
my_tuple = (1, 2, 3)
my_list = [1, 2, 3]
# Using tuple as a key works
my_dict[my_tuple] = "Tuple key"
# Trying to use list as a key raises an error
try:
my_dict[my_list] = "List key"
except TypeError as e:
error_message = str(e)
print("Dictionary with tuple key:", my_dict)
print("Error message when using list as key:", error_message)When to Use
Use tuples as keys in dictionaries or elements in sets when you need a fixed collection of items that should not change. This is common when you want to represent coordinates, fixed configurations, or composite keys.
Use lists when you need a collection that can change over time, like a shopping list or a list of tasks. Since lists are mutable, they cannot be used as dictionary keys or set elements.
Key Points
- Tuples are immutable and hashable, so they can be dictionary keys or set elements.
- Lists are mutable and unhashable, so they cannot be used as dictionary keys or set elements.
- Hashing requires the object to have a fixed content to keep the hash value consistent.