Intern
220
What is the difference between a list and a tuple?
Answer from AI
sobes.tech AI
The main difference is in mutability. A list is mutable, a tuple is immutable.
- Lists (list)
- Can be modified after creation (adding, removing, changing elements).
- Created using square brackets
[]. - Slightly larger in memory and a bit slower compared to tuples (due to the need to reserve space for future modifications).
- Often used for collections of homogeneous elements, the size of which can change.
- Tuples (tuple)
- Cannot be modified after creation. An attempt to change an element will cause an error.
- Created using parentheses
()(parentheses are optional for tuples with more than one element, but recommended for clarity; for a single-element tuple, a comma is needed). - Slightly smaller in memory and a bit faster compared to lists.
- Often used to store heterogeneous elements representing a single entity (e.g., coordinates
(x, y)) or as dictionary keys (since they are hashable due to their immutability).
# List example
my_list = [1, 2, 3]
my_list.append(4) # Modification is possible
print(my_list)
# Tuple example
my_tuple = (1, 2, 3)
# my_tuple.append(4) # This will raise AttributeError
print(my_tuple)