What does this print?
import copy
a = [[1], [2]]
b = copy.copy(a)
b[0].append(9)
print(a)Options
- [[1], [2]]
- [[1, 9], [2]] (Correct option)
- [[1], [2], 9]
- [[9], [2]]
Answer
[[1, 9], [2]]
Why
copy.copy creates a new outer list, but the items inside are the SAME inner lists, not copies.
So b[0] and a[0] are one and the same list; appending to it shows up in both.
copy.deepcopy copies everything recursively, so nothing is shared.
Remember
Shallow copy = new container, same contents.