Python Lists vs Tuples: Mutability, Memory, and Use Cases
StringsModel answerLast updated
Compare Python lists and tuples across mutability, memory layout, hashability, and idiomatic use, including tricky edge cases.
Python provides two built-in sequence types that look similar on the surface but behave quite differently in practice: list and tuple. Both are ordered, both support indexing and slicing, and both can hold any mix of object types. Yet experienced Python developers choose between them deliberately.
Explain the key differences between a list and a tuple. Your answer should cover:
- Mutability — what it means, what operations it enables or forbids, and why immutability being shallow matters
- Performance and memory — at a high level, how each type allocates memory and where speed differences come from
- Typical use cases — when you would reach for each one, and a useful heuristic for deciding
- Hashability — why tuples can serve as dictionary keys but lists cannot, and under what conditions a tuple itself is not hashable
- At least one code snippet that illustrates a meaningful or surprising difference
Note any gotchas or edge cases a working Python programmer should know.
Hints
Hint 1
Ask yourself: what single property explains almost every other difference between the two types — hashability, memory layout, safe use as constants, all of it?
Hint 2
Think about what 'shallow immutability' means. A tuple cannot change which objects it references, but can those objects change? What does that imply for hashability of a tuple containing a list?
Hint 3
Consider the += operator on both types. For a list, does it mutate in place or create a new object? For a tuple? What happens to other variables that reference the same object?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core Distinction
The single property that explains nearly every difference is mutability. A list is mutable — you can add, remove, or replace elements after creation. A tuple is immutable — once created, neither its length nor the references it holds can change. Hashability, memory layout, idiomatic use, and several gotchas all follow from this.
Mutability and Its Implications
Lists expose a rich set of in-place operations: append, extend, insert, pop, remove, sort, reverse, item assignment (xs[i] = v), slice assignment, and del. Tuples expose only count and index.
Immutability is shallow. A tuple fixes which objects it points to, not the internal state of those objects. A tuple containing a list still allows that inner list to be mutated:
record = ([1, 2], "x")
record[0].append(3)
print(record) # ([1, 2, 3], 'x') — the tuple's reference didn't change, but its content did
Three practical implications worth calling out:
Aliasing safety. Passing a tuple to a function gives you a guarantee its structure won't be altered. Passing a list does not — any alias to that list can mutate it, and all other aliases see the change immediately. The classic version of this bug is a mutable default argument: def f(x=[]) shares the same list object across every call that uses the default.
+= rebinds tuples but mutates lists. On a list, a += [4] modifies the list in place, so every variable pointing at it sees the update. On a tuple, t += (4,) constructs a new tuple and rebinds t — other references still see the old value.
a = [1, 2]; b = a
b += [4]
print(a) # [1, 2, 4] — alias affected
t = (1, 2); u = t
u += (4,)
print(t, u) # (1, 2) (1, 2, 4) — original untouched
The +=-inside-a-tuple gotcha. Given t = ([1, 2], "x"), executing t[0] += [3] raises TypeError: 'tuple' object does not support item assignment but still mutates the inner list. The in-place list extension succeeds first; only the subsequent write-back into the tuple slot fails. The exception fires and the mutation sticks — a surprising outcome that trips up even experienced developers.
Performance and Memory
These are CPython specifics; exact numbers vary by version.
Memory layout. A tuple stores its element pointers in one contiguous, fixed-size allocation. A list holds a pointer to a separately allocated, over-allocated array — that extra capacity is what makes append amortized O(1), but it means a list always occupies more memory than an equivalent tuple. On 64-bit CPython, an empty tuple is roughly 40 bytes versus ~56 for an empty list.
Creation speed. A tuple literal of constants (e.g., (1, 2, 3)) is folded into a constant at compile time and can be reused. A list literal allocates a new object on every execution. CPython also caches small tuples in a free list. Tuple creation is therefore measurably faster, though rarely the bottleneck.
Access speed. Indexing and iteration are essentially identical for both.
| Operation | list | tuple |
|---|---|---|
Index x[i] | O(1) | O(1) |
v in x | O(n) | O(n) |
| Slice of length k | O(k) | O(k) |
append | amortized O(1) | not available |
| Insert/delete at front | O(n) | not available |
Choose between them based on semantics. Micro-benchmarking list vs. tuple access is rarely meaningful.
Typical Use Cases
Reach for a list when you have a variable-length collection of similar items you'll build up, filter, or sort: rows from a file, a job queue, accumulating results.
Reach for a tuple when you have a fixed-size record whose positions carry meaning: (latitude, longitude), (user_id, timestamp), an RGB triple. collections.namedtuple and typing.NamedTuple add field names while keeping the tuple's properties. Tuples are also the natural shape for returning multiple values from a function and for read-only constants.
A useful heuristic: lists are for homogeneous sequences of unknown length; tuples are for heterogeneous structures of known shape.
Hashability and Dictionary Keys
Hash tables (dicts and sets) require keys whose hash value never changes after insertion. A mutable object's hash could go stale the moment it's modified, corrupting the table.
- Lists are never hashable.
list.__hash__is explicitly set toNone. - A tuple is hashable only if every element it contains is hashable, checked recursively.
(1, "a", (2, 3))is hashable.(1, [2, 3])is not — callinghashon it raisesTypeError.
visited = {}
visited[(0, 0)] = True # fine — tuple key
visited[(2, 3)] = True
try:
visited[[0, 0]] = True # TypeError: unhashable type: 'list'
except TypeError as e:
print(e)
try:
hash(([1, 2], "x")) # TypeError: unhashable type: 'list'
except TypeError as e:
print(e)
This comes up constantly: grid coordinates as dict keys, composite cache keys for memoization (functools.lru_cache requires hashable arguments), and deduplicating a list of lists via set(map(tuple, rows)).
Edge Cases Worth Knowing
- Single-element tuples require a trailing comma.
(5)is the integer5.(5,)is a one-element tuple. The comma creates the tuple, not the parentheses. - Building a tuple in a loop with
+=is O(n²). Eacht += (x,)copies the whole tuple. Build a list and calltuple(xs)once at the end. - Type conversion is a shallow copy.
list(tup)andtuple(lst)create a new container referencing the same element objects. - Cross-type equality is always
False.[1, 2] == (1, 2)returnsFalseeven though the contents match, because the types differ.
Common Mistakes
- Claiming tuples are "faster for iteration" without qualification — access speed is virtually the same; creation speed is where the gap is real.
- Saying a tuple is immutable and therefore always hashable — the "all elements must be hashable" rule catches many people off guard.
- Forgetting the trailing comma on a single-element tuple —
("error")is just a string in parentheses. - Over-using lists everywhere by habit, passing them into functions that only need to read — a tuple signals intent and prevents accidental mutation.