Names, mutable objects, and copies

3.15.2

See when two names share an object and choose how to copy a nested collection.

On this page

Assignment and mutation

Assignment binds a name to an object. After alias = original, both names refer to the same list. Mutating the list through either name changes what both can see. Assigning alias to a different list later changes only that binding.

original = [10, 20]
alias = original
alias.append(30)
print(original)
alias = [5]
print(original, alias)
Both names point to [10, 20, 30] after the append. Reassignment then makes alias point to [5]. Download image
Changing the list and changing what a name points to have different effects.
Example output
[10, 20, 30]
[10, 20, 30] [5]

Shallow and deep copies

A shallow copy makes a new outer list and reuses references to its elements. A nested mutable list is therefore still shared. deepcopy creates independent copies of nested lists in this example. Copy only as much as the code needs.

from copy import deepcopy

original = [[10], [20]]
shallow = original.copy()
deep = deepcopy(original)

original[0].append(15)
print(shallow)
print(deep)
Three separate outer lists. Original and shallow show [10, 15] for the first inner list, while deep shows [10]. Download image
The mutation reaches the shallow copy through the shared inner list.
Example output
[[10, 15], [20]]
[[10], [20]]

Official references