Middle
What is the difference between list and tuple in Python?
sobes.tech AI
Answer from AI
Main differences between list and tuple in Python:
- Mutability:
listis a mutable data type, elements can be added, removed, or changed;tupleis immutable, cannot be changed after creation. - Syntax: lists are created with square brackets
[], tuples with parentheses(). - Usage: tuples are often used to store fixed sets of data where immutability is important, lists are used for dynamic collections.
- Performance: tuples occupy less memory and are slightly faster than lists.
Example:
my_list = [1, 2, 3]
my_list.append(4) # list can be modified
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # will cause an error, tuple is immutable
Choosing between them depends on the task and whether data needs to be modified.