Hone

Lessons · Python · shallow vs deep copy

A copy that is not all the way down

list(x) or x[:] copies the outer list, but the items inside are the same objects. Nested lists are still shared.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

You copy a grid, change one cell in the copy, and the original changes too. Everyone hits this once; knowing 'shallow versus deep' ends it.

How to think about it

Ask: does the thing contain other containers? Flat list of numbers or strings: a shallow copy is fine. Lists of lists, dicts of lists: copy.deepcopy, or build the copy yourself.

Worked example

grid = [[0, 0], [0, 0]]
A list of lists.
g2 = grid[:]
Shallow: g2 is a new outer list, but its rows are grid's rows.
g2[0][0] = 9
Changes the shared row.
print(grid)
[[9, 0], [0, 0]]. The original changed.
import copy; g3 = copy.deepcopy(grid)
Independent all the way down.

Your turn

Copy a nested structure independently.

import copy
backup = copy.(config)

The trap

[[0] * 3] * 3 makes three references to ONE row. Use [[0] * 3 for _ in range(3)].

Practise shallow vs deep copy on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.