Junior
What is the difference between a list and a tuple in Python?
sobes.tech AI
Answer from AI
A list (list) and a tuple (tuple) in Python are both ordered collections of elements, but there are key differences:
- Mutability: lists are mutable (elements can be added, removed, changed), tuples are immutable.
- Syntax: lists are created with square brackets
[], tuples with parentheses()or without brackets if elements are separated by commas. - Usage: tuples are often used to store fixed sets of data, such as coordinates, or as keys in dictionaries (since they are hashable), while lists are used for dynamic collections.
Example:
my_list = [1, 2, 3]
my_list[0] = 10 # Can be changed
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # Error: tuple is immutable
Thus, the choice between a list and a tuple depends on whether you need to modify the data and the requirements of the structure.