Senior
Sõnastike kontekstis, mis vahe on nimekirja ja tupi vahel?
sobes.tech AI
Vastus AI-lt
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'
Therefore, tuples are suitable for composite keys in dictionaries, while lists are not.