Skip to content

Question 8

What is the output of the following code?

1
2
3
4
ls1 = [['p', 'q'], 'x', ['p', 'q']]
ls2 = ls1[1:]
ls2[1][1] = 's'
print(ls1)
Hint

Watch out for shallow copies in any of the list's elements!

Solution

Given ls1 = [['p', 'q'], 'x', ['p', 'q']], ls2 = ls1[1:] makes its own copies of values 'x' and ['p', 'q']. Hence, ls2 evaluates to ['x', ['p', 'q']].

However, ['p', 'q'] is a shallow copy from ls1. We can consider the two lists in both ls1 and ls2 to be different containers with linked elements. Specifically, if we were to replace ls2[1] with another value, say ['a'], this does not change the last ['p', 'q'] value in ls1. However, if we were to modify the contents of any of these two lists, it will reflect on the other as well. For instance, executing ls1[2][0] = 'a' will make both ls1[2] and ls2[1] to reflect the same change, i.e., ls1[2] = ls2[1] = ['a', 'q']. Therefore, when executing ls2[1][1] = 's' after defining ls2, this means that ls2[1] = ls1[2] = ['p', 's'].

Hence, ls1 = [['p', 'q'], 'x', ['p', 's']].

Answer
[['p', 'q'], 'x', ['p', 's']]