11 / 14

What is the difference between a list and a tuple, and when would you choose one over the other?

Difficulty: 2/10
Lists, Tuples, Mutability

List vs tuple: mutability, semantics, and trade-offs

A list is a mutable sequence: you can add, remove, or replace elements in place. A tuple is an immutable sequence: once built, its element references cannot be changed. The deeper reason tuple exists is semantic and operational: immutability makes it hashable when all elements are hashable, so it can be used as a dict key or set member, and it signals a fixed record-like structure. CPython also stores tuples slightly more compactly because it does not need overallocation for growth.

  1. 1

    Choose a list for homogeneous, growing/shrinking collections, queues/stacks at the end, or when in-place updates are expected.

  2. 2

    Choose a tuple for fixed records, multiple return values, dict keys, set members, and read-only configuration.

  3. 3

    Trade-off: namedtuple/dataclass can be clearer than a raw tuple for record semantics; dataclass gives mutability control and methods, namedtuple keeps tuple behavior.

  4. 4

    Common mistake: thinking tuple immutability is deep. A tuple can contain a list, and that list can still be mutated.

  5. 5

    Version note: dict/set key hashability depends on all tuple elements being hashable; this is not version-specific, but tuple memory/overallocation details are CPython implementation details.

javascript

Scenario Questions

0-2 years experience

  1. 1You need to return three values from a function and callers must not be able to modify the returned collection in place. What do you return and why?
  2. 2You are storing coordinates as dict keys. Which collection do you use and what restriction applies?

2-5 years experience

  1. 1A config loader returns a list of DB hosts. Another module accidentally appends to it and corrupts global config. How do you redesign the return type?
  2. 2You need to group records by a composite key of user_id and date. Which collection type for the key and why?

5-8 years experience

  1. 1You are designing an event schema with fixed fields but occasional optional metadata. Would you use tuple, namedtuple, dataclass, or dict? Discuss memory and API stability.
  2. 2A high-throughput pipeline emits millions of small records. How would list vs tuple affect memory and cache behavior?

8+ years experience

  1. 1Design an immutable value object that can be safely shared across threads and used as a cache key, while still supporting schema evolution.
  2. 2You need to expose a fixed-shape tensor-like result to C extensions. What Python sequence type minimizes overhead and why?

Follow-up Questions

  • Can a tuple contain a list? What happens if you try to use that tuple as a dict key?
  • When would you prefer a dataclass over a namedtuple or a plain tuple?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.