Sobes.tech
Junior — Middle

Is it possible to use a list as a key in a dictionary?

sobes.tech AI

Answer from AI

In most programming languages, lists (or arrays) are mutable objects and cannot be used as keys in dictionaries (hash tables) because keys must be immutable and hashable.

For example, in Python, a list (list) cannot be used as a dictionary key because it is mutable and does not have a hash function:

my_dict = {}
my_list = [1, 2, 3]
my_dict[my_list] = 'value'  # will raise a TypeError

If you need to use a sequence as a key, you can use a tuple (tuple), which is immutable and hashable:

my_dict = {}
my_tuple = (1, 2, 3)
my_dict[my_tuple] = 'value'  # works correctly

Thus, a list as a key is not allowed, but immutable data structures are.