liveBook · Manning

Deep copy

As explained in The Quick Python Book, Fourth Edition

A deep copy is a recursively independent copy of a container and the modifiable objects nested within it.

A deep copy creates an independent copy of a container and the modifiable objects nested inside it. Unlike a shallow copy, changing a nested list or dictionary in the copy does not change the original. section 5.6 section 7.2

Choose the copy technique according to the structure being copied:

  • Use a full slice, +, *, or a container's copy method for a shallow copy when nested objects do not need independent copies. section 5.6 section 7.2
  • Use copy.deepcopy when nested lists, dictionaries, or other modifiable objects must be changed without side effects on the original. section 5.6 section 7.2

Copying a nested list

import copy original = [[0], 1] shallow = original[:] deep = copy.deepcopy(original) shallow[0][0] = 'zero' # original becomes [['zero'], 1] deep[0][0] = 5 # original remains [['zero'], 1]

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains shallow references, demonstrates nested mutations, and stops short of implementation internals.
Examples
Demonstrates nested lists, slicing, copy.deepcopy, and mutations through shallow and deep copies.
What you can do after
Apply it via Python's copy module to isolate nested mutable objects before changing copied data.
How it connects
Connects deep copy with shallow copy, lists, dictionaries, and the copy module.

Also explained in

Compare how 5 books explain deep copy →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.