Sobes.tech
Junior — Middle

Why can't a list be used as a key for a dictionary in Python?

sobes.tech AI

Answer from AI

In Python, dictionary keys must be hashable (immutable) to ensure their values remain constant when used in a hash table. Lists are mutable objects, so they cannot be hashable and cannot be used as dictionary keys. If you need to use a sequence as a key, you can use a tuple, which is an immutable and hashable type.

Example:

my_dict = {}
my_dict[[1, 2, 3]] = "value"  # Error TypeError

my_dict[(1, 2, 3)] = "value"  # Works correctly
Why can't a list be used as a key for a dictionary in… - sobes.tech