DEV Community

BigOSlate
BigOSlate

Posted on Originally published at bigoslate.com

The Python [:] Shallow Copy Bug That Mutates Nested Lists in Production

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)             # ???
Enter fullscreen mode Exit fullscreen mode

Most developers expect [[1, 2], [3, 4]]. Instead, Python prints:

[[999, 2], [3, 4]]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode
  • Rebinding a top-level slot (backup[0] = [7, 8]) only changes backup's outer pointer (board stays untouched).
  • Mutating inside a nested object (backup[0][0] = 999) follows ptr_row0 to 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]]
Enter fullscreen mode Exit fullscreen mode

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!
Enter fullscreen mode Exit fullscreen mode

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)