[Tutor] insering into lists through slices
alan.gauld at freenet.co.uk
Fri Jun 3 21:07:33 CEST 2005
> I simply fail to understand the semantics of the following piece of
> #assuming ls=[1,2,3,4]
> #then ls becomes
> >>> ls
> [1, 5, 6, 2, 3, 4]
> Basically, ls[1:1] returns an empty list and assigning [5,6] to
> it, actually inserts the elements... but how?
ls[1:1] returns whatever lies between ls item 1 and ls item 1
which is nothing.
ls[1:1] = [5.6] inserts the contents of [5,6] between ls item 1
and ls item 1 - in other words at index 1 - which results in
So the behaviour of [1:1] is consistent, it refers to the items
between index 1 and 1.
Similarly ls[2:3] refers to whats between 2 and 3 which is 3
ls[2,3 = [5,6] replaces whats between 2 and 3 with 5,6 so the result
Note that the numbers in a slice refer to the commas not the
list indexes (to take a simplistic view, for a more accurate
one read the docs onslicing!)
Author of the Learn to Program web tutor
More information about the Tutor