I know that Slicing lists does not generate copies of the objects in the list; it just copies the references to them.
But if that\'s the case, then why doesn\'t this wor
For the sake of explaining it better, assume you had written
l = [1, 2, 3]
k = l[0:2]
k[-1] = 10
I hope you can agree that this is equivalent.
Now let's break down the individual statements:
l = [1, 2, 3]This creates the following objects and references:
id object
-- --------
0
1
2
3
name → id
---- --
l → 3
l[0] → 0
l[1] → 1
l[2] → 2
k = l[0:2]This creates a new list containing copies of the references contained in l:
id object -- -------- 01 2 3 4
name → id ---- -- l → 3 l[0] → 0 l[1] → 1 l[2] → 2 k → 4 k[0] → 0 (copy of l[0]) k[1] → 1 (copy of l[1])
k[-1] = 10First, index −1 resolves to index 1 (because k has length 2), so this is equivalent to k[1] = 10. This assignment means that the objects and references are updated as such:
id object -- -------- 01 2 3 4
5
name → id ---- -- l → 3 l[0] → 0 l[1] → 1 l[2] → 2 k → 4 k[0] → 0 k[1] → 5
Note how l and l[0] to l[2] are not affected by this. QED.