Junior — Middle
What is the difference between using a tuple and a list in Python?
sobes.tech AI
Answer from AI
Main differences between a tuple and a list in Python:
- Mutability: a list is mutable, a tuple is immutable. This means that after creating a tuple, you cannot change its contents (add, delete, or modify elements).
- Usage: tuples are often used to store fixed sets of data, such as coordinates, or as keys in dictionaries because they are hashable. Lists are convenient for dynamic data modification.
- Performance: tuples generally occupy less memory and are slightly faster than lists.
Example:
lst = [1, 2, 3]
lst[0] = 10 # works
tpl = (1, 2, 3)
tpl[0] = 10 # will raise a TypeError
The choice depends on the task: if the data should not change, it is better to use a tuple.