Skip to the solution
EasyDSA10 min read

What is the difference between a list and a tuple?

549 views

The problem

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 list is mutable (append, insert, remove, assign by index), a tuple is 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 namedtuple names 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 append is amortised O(1).

Code / implementation expected: Optional β€” a few lines showing mutation, a tuple as a dict key and (1,) vs (1).

  • python
  • basics

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonMutability, the two tuple methods, the comma, dict keys and size
PythonConstant folding with dis, conversions and namedtuple

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 20 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

What set operations does Python support?

Continue