Question presented to candidate: "Lists and tuples both hold an ordered sequence of items. What is actually different between them, and how do you decide which one to use?"
What a strong answer should cover:
- The core distinction: a
listis mutable (append, insert, remove, assign by index), atupleis immutable once created. - Consequences: a tuple is hashable when its items are, so it can be a dict key or set member; a list never can. Tuple immutability is shallow.
- Intent: a list is a variable-length collection of similar items; a tuple is a fixed-size record whose positions mean something (coordinates, a row, a function returning several values), and
namedtuplenames those positions. - Syntax traps: the comma makes a tuple, so
(1)is an int and(1,)is a tuple; packing and unpacking. - CPython detail: a tuple stores its items inline with no spare capacity (smaller), the compiler folds a tuple of constants into one constant, and a list over-allocates so
appendis amortised O(1).
Code / implementation expected: Optional β a few lines showing mutation, a tuple as a dict key and (1,) vs (1).