References and copies
Names point at objects. Assignment, copy.copy and copy.deepcopy differ only in how many objects they create.
- Draw the reference graph for a nested list
- Predict what changes after assignment, a shallow copy and a deep copy
- Choose the right copy for a given data structure
A Python variable is not a box holding a value. It is a name bound to an object, and a list is an object holding references to more objects. d_deepcopy.py makes a deep copy of a nested list and shows that changing the copy leaves the original alone:
import copy
original_list = [[1, 2, 3], [4, 5, 6]]
copied_list = copy.deepcopy(original_list)
copied_list[0][0] = 100
# original list [[1, 2, 3], [4, 5, 6]]
# copied list [[100, 2, 3], [4, 5, 6]]
The interesting question is what the other two options do.
- Assignment,
copied = original_list, creates no object at all. Both names are bound to the same list, so every change is visible through both. - Shallow copy,
copy.copy(original_list)(ororiginal_list[:]), creates one new outer list whose slots point at the same inner lists.copied.append([7])leaves the original alone, butcopied[0][0] = 100reaches through a shared inner list and changesoriginal_listtoo. - Deep copy copies recursively: new outer list, new inner lists. Nothing is shared, which is what the script demonstrates.
Running the shallow version confirms it: after copied[0][0] = 100, original_list is [[100, 2, 3], [4, 5, 6]], while copied is original_list is False and copied[0] is original_list[0] is True.
Which one to use
A shallow copy is enough — and much cheaper — when the elements are immutable, such as a list of numbers or strings. Use deepcopy when the structure nests mutable objects that you intend to change independently. It handles shared and even circular references correctly by remembering what it has already copied.
The same reference rules explain the classic default-argument trap: def f(x, acc=[]) creates one list when the function is defined, and every call shares it.
Try it yourself. Predict the output of grid = [[0] * 3] * 3; grid[0][0] = 1; print(grid), then draw its reference graph. Rewrite it with a comprehension so each row is a separate list.