slicing and parallel assignment: inconsistent behaviour??

Lutz.Wendland Lutz.Wendland at student.uni-ulm.de
Thu Jul 18 12:49:57 EDT 2002


tjd at sfu.ca (Toby Donaldson) wrote in message 
> I was hoping someone might be able to help me with a problem I've run
> into with slices and parallel assignment. I want to swap to segments
> of a list. For instance:
> 
>     >>> B = range(10)
>     >>> B[1:5], B[5:10] = B[5:10], B[1:5]
>     >>> B
>     [0, 5, 6, 7, 8, 1, 2, 3, 4, 9]

The list B has 10 elements. And the indices into the list are like this:

   B:         [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
              |   |   |   |   |   |   |   |   |   |   |
   Indices:   0   1   2   3   4   5   6   7   8   9   10

1) The slice B[1:5] spans over four elements and is substituted by
a sclice B[5:10] which spans over five elements. That is, B is enlargened
by one element:

   B:         [ 0 , 5 , 6 , 7 , 8 , 9 , 5 , 6 , 7 , 8 , 9 ]
              |   |   |   |   |   |   |   |   |   |   |   |
   Indices:   0   1   2   3   4   5   6   7   8   9   10  11

2) Now the sclice B[5:10], which is [9, 5, 6, 7, 8], is substituted by
the slice B[1:5] of the original B: B[1:5] is [1,2,3,4],
and we get B as [0, 5, 6, 7, 8, 1, 2, 3, 4, 9].

> This works as I expect. But if I leave out the 10s in the slice

... they stretch right to the end of B. This affects only
the second step of the assignment as in 2):
(since in the first step, B[5:] is identical to B[5:])

2a) The sclice B[5:], which is [9, 5, 6, 7, 8, 9], stretches now over
6 elements, and is substituted by the slice B[1:5] of the
original B, which is [1,2,3,4],
and we get B as [0, 5, 6, 7, 8, 1, 2, 3, 4].

> indices, I get this:
> 
>     >>> A = range(10)
>     >>> A[1:5], A[5:] = A[5:], A[1:5]
>     >>> A
>     [0, 5, 6, 7, 8, 1, 2, 3, 4]
> 
> Where has the 9 gone? 

It has been substituted as part of A[5:] which is [9,5,6,7,8,9].

I hope not being too unclear or too exhaustive.

Lutz.



More information about the Python-list mailing list