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)
Download image
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)
Download image
Example output
[[10, 15], [20]] [[10], [20]]