[Tutor] insering into lists through slices

Alan G 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
code.
>  #assuming ls=[1,2,3,4]
>  >>>ls[1:1]=[5,6]
> #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
[1,5,6,2,3,4]

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
is:
[1,2,5,6,4]

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!)

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list