Skip to main content
Interviewpedia

When would you use a tuple rather than a list?

Technical · Fresher

Answer guide

Read the answer guide

Choose a tuple for a small fixed record whose shape does not change, such as a coordinate pair or a row returned from a query, and a list for a collection that grows, shrinks or is reordered. Tuples signal intent to readers and can be used as dictionary keys when everything inside is hashable. Be careful: a tuple only fixes which objects it holds, so a list stored inside can still be modified. A simple rule is that position carries meaning for tuples and repetition carries meaning for lists.

What the interviewer is assessing

Whether you can pick a data structure by intent and understand what immutability does and does not guarantee.

Common mistakes

  • Says tuples are just faster lists and ignores the meaning they convey.
  • Claims everything inside a tuple is frozen, forgetting a contained list can change.

Practise a follow-up

  • Can a tuple containing a list be a dictionary key?
  • When would a named tuple or dataclass be clearer than a plain tuple?
Practise this question →

Worked example: defaults and shared state

Run this with Python 3. Defaults are created at definition time. The tuple example shows why an immutable outer container does not guarantee immutable contents.

def add_bad(item, items=[]):
    items.append(item)
    return items

print(add_bad("a"))
print(add_bad("b"))

def add_good(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

print(add_good("a"))
print(add_good("b"))

def add_tuple(item, holder=([],)):
    holder[0].append(item)
    return holder

print(add_tuple("a"))
print(add_tuple("b"))

Expected output

['a']
['a', 'b']
['a']
['b']
(['a'],)
(['a', 'b'],)

Use the None sentinel when omitted arguments should produce independent lists. Passing an explicit list still deliberately shares that caller-owned object.

Source: Python documentation: default argument values.