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.
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
- Recursively copies everything.
- Preserves sharing and cycles.
- Costs more than a shallow copy.
Code examples
Independent nested data
[[1, 2], [3, 4]] [[1, 2, 99], [3, 4]] False
Shared references and cycles
{'a': [0, 1], 'b': [0, 1]} True
True FalseMore examples
Undo with snapshots
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:
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
Prefer
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
- 1Create a nested settings template and generate three independent user copies with different nested values.
- 2Add 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?