copy
Assignment never copies — it gives the same object a second name. copy.copy makes a new outer container that still shares the items inside; copy.deepcopy copies everything, all the way down.
import copy from copy import deepcopy
Demo
import copy original = [[1, 2], [3]] shallow = copy.copy(original) deep = copy.deepcopy(original) original[0].append(9) (original, shallow, deep)
Appending 9 to original[0] changes the shallow copy too — ([[1, 2, 9], [3]], [[1, 2, 9], [3]], [[1, 2], [3]]) — because copy.copy built a new outer list holding the SAME inner lists. Only the deep copy has its own inner lists. With plain assignment even the outer list is shared: alias shows the appended 3, clone does not.
Members
Common patterns
import copy snapshot = copy.deepcopy(state)
grid_copy = [row[:] for row in grid]
import copy moved = copy.replace(point, x=point.x + 1)
import copy class Model: def __deepcopy__(self, memo): new = Model.__new__(Model) new.data = copy.deepcopy(self.data, memo) new.cache = self.cache # shared on purpose return new
Examples
Pitfalls
grid = [[0] * 3] * 3 grid[0][0] = 1 grid
grid = [[0] * 3 for _ in range(3)] grid[0][0] = 1 grid
settings = {'tags': ['a']} backup = settings.copy() settings['tags'].append('b') backup
import copy settings = {'tags': ['a']} backup = copy.deepcopy(settings) settings['tags'].append('b') backup
When to use
- Snapshots of nested, mutable state before changing it
- Duplicating objects whose class you do not control
- copy.replace: "the same, but with this field changed" for immutable records
- Flat lists and dicts → list.copy(), dict.copy() or a slice (same result, clearer)
- Huge object graphs in hot loops → deepcopy is slow; restructure or copy only what changes
- Objects holding files, sockets, locks → they cannot be copied
Notes
FAQ
A shallow copy (copy.copy, list.copy, dict.copy, slicing) creates a new outer container but puts the same inner objects in it. A deep copy (copy.deepcopy) also copies those inner objects, recursively, so nothing mutable is shared with the original.