Look at these 4 lines of Python. What gets printed on the last line?
board = [[1, 2], [3, 4]]
backup = board[:] # Or board.copy(), or list(board)
backup[0][0] = 999
print(board) # ???
Most developers expect [[1, 2], [3, 4]]. Instead, Python prints:
[[999, 2], [3, 4]]
Your backup silently mutated board! Here is why this happens in RAM—and the bonus [[0] * 3] * 3 trap every Python interview loves testing.
What board[:] Actually Copies in Memory
In Python, lists don't store objects inside contiguous value boxes—they store memory references (pointers) to objects on the heap.
A shallow copy (board[:], board.copy(), or list(board)) allocates a brand-new outer list container, and copies the top-level pointers into it:
board ──► [ ptr_row0 , ptr_row1 ] (Outer list #1)
│ │
▼ ▼
[999, 2] [3, 4] (SHARED inner lists in RAM!)
▲ ▲
│ │
backup ──► [ ptr_row0 , ptr_row1 ] (Outer list #2)
- Rebinding a top-level slot (
backup[0] = [7, 8]) only changesbackup's outer pointer (boardstays untouched). - Mutating inside a nested object (
backup[0][0] = 999) followsptr_row0to the exact same inner list both variables share!
Bonus Trap: Never Build a 2D Grid With [[0] * C] * R!
# ❌ BUG: Multiplies 3 pointers to the EXACT SAME single inner row!
bad_grid = [[0] * 3] * 3
bad_grid[0][1] = 1
print(bad_grid) # [[0, 1, 0], [0, 1, 0], [0, 1, 0]] <-- All 3 rows changed!
# ✅ FIX: List comprehension evaluates [0] * 3 fresh on every iteration
good_grid = [[0] * 3 for _ in range(3)]
good_grid[0][1] = 1
print(good_grid) # [[0, 1, 0], [0, 0, 0], [0, 0, 0]]
When You Need a True Independent Clone: copy.deepcopy()
Whenever a list or dictionary contains nested mutable objects (inner lists, dicts, or class instances), use copy.deepcopy:
import copy
board = [[1, 2], [3, 4]]
safe_backup = copy.deepcopy(board)
safe_backup[0][0] = 999
print(board) # [[1, 2], [3, 4]] — 100% isolated!
Trace Python Memory & Slicing Step-by-Step
Want to step through CPython variables, list references, and slicing line-by-line in a live RAM visualiser?
👉 Explore the Free Visual Python Lists & Slicing Lesson on BigOSlate
Top comments (0)