7

In the official Python Tutorial (2.7), it is said that slice makes a shallow copy of the list (for eg) and each item in a slice is a reference to the original list object.

For eg, doing

a = [1,2,3]
a[:][0] = 2

will not change the actual value cause what happens is merely the first item in the slice is referenced to a new object (which is 2).

However, doing

a[:] = [] # or any other list

will actually change the list.

Can anybody explain that?

pspencil
  • 295
  • 1
  • 10
  • 1
    This works for less than the full slice too, try `a[:2] = [5, 6]` – jonrsharpe Aug 08 '14 at 10:13
  • Slicing will return a new list where each element is a shallow copy of the original list: `a = [1, 2, 3]; s = a[:]; id(a) != id(s); id(a[0]) == id(s[0])`. – Germano Aug 08 '14 at 10:30

0 Answers0