Python Practice Question 4: Shallow Copy Nested List
Python · Test 1 · question 4 of 10
What does this code print? a = [[1], [2]]; b = a.copy(); b[0].append(9); b.append([3]); print(a)
Show answer and explanation
Answer:
list.copy() (like a[:], list(a) and copy.copy(a)) makes a shallow copy: a new outer list whose slots hold references to the *same* inner objects. So b is a different list from a, but b[0] and a[0] are the same [1] list.
b[0].append(9) mutates that shared inner list, so the change is visible through a as [1, 9]. b.append([3]) changes only the outer list b, which is a separate object, so a keeps its two elements. Result: [[1, 9], [2]].
Option A is what you would get from copy.deepcopy(a), which recursively copies the inner lists too.
Option B is what you would get from b = a, no copy at all, both names bound to one list.
Option C gets the two effects backwards: it assumes the outer append is shared and the inner mutation is not, which is the opposite of how a shallow copy behaves.
Reference: copy - Shallow and deep copy operations