Skip to content

Module 17 · Advanced Python Concepts — topic 4 of 14

Deep copy

Fully independent copies with copy.deepcopy: recursively copying nested containers and objects, preserving shared references and cycles, performance considerations, customising with __deepcopy__, and an undo-history example.

Beginner 8 min read·Lesson 250 of 306 in Python Programming

Learning objectives

  • Create independent copies of nested data
  • Explain how deepcopy handles shared references and cycles
  • Use deep copies for snapshots and undo

Definition

A deep copy recursively copies an object and everything it contains, producing a completely independent structure. copy.deepcopy also remembers objects it has already copied, so shared references and cycles are reproduced correctly.

Introduction

To keep a snapshot of a game board or a configuration before changing it, every nested list and dictionary must be copied, not just the outer container.

Why it matters

Deep copies prevent hidden sharing in nested data, which is essential for undo features, simulations and safely modifying templates.

Detailed explanation

copy.deepcopy(obj) copies the object, then recursively copies everything it references.

Immutable atoms such as numbers and strings are not duplicated (there is no need), but every mutable container and object is.

deepcopy keeps a memo of already-copied objects: if two places referred to the same list, both refer to the same new list in the copy, and self-referencing cycles don't cause infinite recursion.

Deep copying large structures takes time and memory; copy only when you need independence.

Some objects can't be meaningfully copied, such as open files, network connections and locks; deepcopy may fail or share them.

Classes can control deep copying with a __deepcopy__(self, memo) method.

A serialisation round trip (json.loads(json.dumps(x))) also produces a deep copy, but only for JSON-compatible data.

Syntax

Python
import copy
snapshot = copy.deepcopy(state)
state["board"][0][0] = "X" # snapshot unchanged
  • Recursively copies everything.
  • Preserves sharing and cycles.
  • Costs more than a shallow copy.

Code examples

Independent nested data

Python
import copy
orig = [[1, 2], [3, 4]]
deep = copy.deepcopy(orig)
deep[0].append(99)
print(orig, deep, orig[0] is deep[0])
Output
[[1, 2], [3, 4]] [[1, 2, 99], [3, 4]] False

Shared references and cycles

Python
import copy
shared = [0]
data = {"a": shared, "b": shared}
d2 = copy.deepcopy(data)
d2["a"].append(1)
print(d2, d2["a"] is d2["b"])
cyc = [1]
cyc.append(cyc)
cc = copy.deepcopy(cyc)
print(cc[1] is cc, cc is cyc)
Output
{'a': [0, 1], 'b': [0, 1]} True
True False

More examples

Undo with snapshots

Python
import copy
state = {"turn": 1, "board": [["", "", ""], ["", "", ""], ["", "", ""]]}
history = []
def move(row, col, mark):
history.append(copy.deepcopy(state))
state["board"][row][col] = mark
state["turn"] += 1
def undo():
global state
state = history.pop()
move(0, 0, "X")
move(1, 1, "O")
print(state["turn"], state["board"][1])
undo()
print(state["turn"], state["board"][1], len(history))
print(history[0]["board"][0])
Output
3 ['', 'O', '']
2 ['', '', ''] 1
['', '', '']

Step-by-step explanation

  • Before each move, a deep copy of the entire state is pushed onto the history.
  • Because the snapshot's board rows are separate lists, later moves don't alter it.
  • undo restores the previous snapshot; the first snapshot still shows the empty starting board.

Expected output

Running “Undo with snapshots” prints exactly:

TextOutput
3 ['', 'O', '']
2 ['', '', ''] 1
['', '', '']

Practical applications

  • Undo/redo in editors and games.
  • Trying out changes on a copy of a configuration template.

Best practices

  • Use deepcopy when nested mutable data must be independent.
  • Prefer storing changes over full snapshots for large states.
  • Avoid deep-copying objects that hold external resources.

Common mistakes

Deep-copying huge data unnecessarily

Avoid

for step in range(10_000):
snapshots.append(copy.deepcopy(big_state))

Prefer

Store only the changes (moves) and replay or reverse them.

Repeated deep copies of large structures use lots of time and memory.

Important notes

  • copy.deepcopy uses the same protocol as pickle, so objects that can be pickled can usually be deep-copied.

Key takeaways

  • deepcopy copies nested structures completely.
  • It preserves shared references and handles cycles.
  • Use it for snapshots and independent templates.

Try it yourself

  1. 1
    Create a nested settings template and generate three independent user copies with different nested values.
  2. 2
    Add redo support to the undo example.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
Practise this topic