Sobes.tech
Senior

In the context of dictionaries, what is the difference between a list and a tuple?

sobes.tech AI

Answer from AI

In the context of dictionaries (for example, in Python), the difference between a list and a tuple is important for dictionary keys:

  • List — a mutable data type, so it cannot be used as a dictionary key because keys must be hashable and immutable.
  • Tuple — an immutable data type, so it can be used as a dictionary key if all its elements are also hashable.

Example:

my_dict = {}
my_dict[(1, 2)] = 'tuple as key'  # Works

my_dict[[1, 2]] = 'list as key'    # Error: TypeError: unhashable type: 'list'

Thus, tuples are suitable for composite keys in dictionaries, but lists are not.

In the context of dictionaries, what is the… - sobes.tech