What is the difference between a list and a tuple in Python, and when would you use each?
py-jun-001
Your answer
Answer as you would in a real interview — explain your thinking, not just the conclusion.
Model answer
A list is mutable — you can append, remove, and replace elements after creation. A tuple is immutable — once created, its contents cannot change. Tuples are slightly more memory-efficient and signal intent: use a tuple for a fixed structure like a coordinate (x, y) or a database row. Lists are for homogeneous collections you need to grow or modify. Tuples are hashable (if all elements are hashable), so they can be used as dictionary keys or set members, which lists cannot. When in doubt: if the data has fixed semantics, use a tuple; if it is a dynamic collection, use a list.
Code example
# List: mutable, ordered
scores = [90, 85, 78]
scores.append(95) # OK
# Tuple: immutable, fixed
point = (10, 20)
# point[0] = 5 # TypeError!
# Tuple as dict key (hashable)
cache = {(1, 2): 'result'}
# NamedTuple for readable fixed structures
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
p = Point(10, 20)
print(p.x, p.y) # 10 20
Follow-up
What is a NamedTuple, and when would you prefer it over a dataclass or a plain tuple?