What is the difference between a list and a tuple in Python?
Lists are mutable (changeable); tuples are immutable (fixed). Use tuples for data that should not change and wherever a hashable sequence is needed.
Python
Overview
Both lists and tuples are ordered sequences, but their mutability differs. Lists can be modified after creation; tuples cannot. This difference has practical implications for correctness, memory, and where each can be used.
Key Points
- •List `[]`: mutable you can append, remove, or change elements.
- •Tuple `()`: immutable once created, elements cannot be changed.
- •Tuples are slightly faster and use less memory than equivalent lists.
- •Tuples can be used as dictionary keys and set elements; lists cannot (they are not hashable).
- •Convention: use tuples for heterogeneous data with fixed meaning (e.g. `(x, y)` coordinate), lists for homogeneous collections you iterate over.
Examples
Mutability difference
pythonmy_list = [1, 2, 3]
my_tuple = (1, 2, 3)
my_list[0] = 99 # OK
my_tuple[0] = 99 # TypeError: 'tuple' object does not support item assignmentTuple as dictionary key (lists cannot)
python# Coordinate lookup
distances = {}
distances[(0, 0)] = 0 # tuple key works
distances[(1, 2)] = 2.24
# distances[[0, 0]] = 0 # TypeError: unhashable type: 'list'Tuple unpacking
pythonpoint = (10, 20)
x, y = point # unpacking
# Functions often return tuples
def min_max(nums):
return min(nums), max(nums)
lo, hi = min_max([3, 1, 4, 1, 5])Pro Tip
A common Python style: if the data is a "record" with a fixed number of named-ish fields, a tuple (or `namedtuple` / `dataclass`) is cleaner. If you'll grow or shrink the collection, use a list.