all Python 3copyterm
copy
module
Shallow and deep copying of objects: copy, deepcopy and replace.
Syntax
import copy
Use it when an object holds mutable nested parts: copy.copy copies only the top level, while copy.deepcopy copies everything recursively. For a list or dict a slice or the copy method also gives a shallow copy. The classic mistake is shallow-copying a list of lists and being surprised that a change in an inner list shows up in both copies.
Examples
import copy
grid = [[0, 0], [0, 0]]
shallow, deep = copy.copy(grid), copy.deepcopy(grid)
grid[0][0] = 9
print(shallow[0][0], deep[0][0]) # → 9 0
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy