MiddleDebuggingOccasionalNot answered yet
Why does mutating the shallow copy change the original?
A copy is taken before mutating it, yet the original changes too.
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
shallow[0].append(99)
print(original)
Find and fix the bug.
copy.copy is shallow: the outer list is new, but the inner lists are shared references, so mutating shallow[0] also changes original → [[1, 2, 99], [3, 4]]. Fix: use copy.deepcopy(original) for fully independent nested data.
- ✗Thinking
copy.copydeep-copies nested structures - ✗Believing a slice
[:]makes inner lists independent - ✗Not reaching for
copy.deepcopyfor nested data
- →When is a shallow copy actually the right choice over a deep copy?
- →How does
copy.deepcopyhandle a structure that contains a reference cycle?