Skip to content

Question 19

What is the output of the following code?

1
2
3
4
5
6
la = [9, 8, 7]
lb = [la, la]
lb[0][0] = 0
lc = [la, la, la]
lc[1][2] = 1
print(lb)
Solution

lb is an independent list containing a linked reference to the value of la, meaning the la values inside lb are mirror copies (proper term: shallow copy) of the original la. This consequently means that any change in either the original or referenced la will reflect itself on the other. Hence, given the statement where lb[0][0] is reassigned to 0, not only does it mean that the first element inside lb becomes [0, 8, 7], but the second element inside lb and the original la take on that same value as well, since they are all linked!

Going by this logic, lc now does the same thing by making shallow copies of la in itself, and after modifying its second element's contents to become [0, 8, 1], every other shallow copy instance of la, be it in lb or elsewhere as well as the original la get modified the same exact way. The changes propagate into lb to then become [[0, 8, 1], [0, 8, 1]], where again the original la it references is now [0, 8, 1].

Answer
[[0, 8, 1], [0, 8, 1]]