slicing and parallel assignment: inconsistent behaviour??

Michael Hudson mwh at python.net
Thu Jul 18 05:56:01 EDT 2002


tjd at sfu.ca (Toby Donaldson) writes:

> Hi,
> 
> 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]
> 
> This works as I expect. But if I leave out the 10s in the slice
> 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 got stomped by the assignment to A[5:].

Writing this out long hand may be clearer:

>>> A[1:5] = t[0]
>>> A
[0, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9]
>>> A[5:]
[9, 5, 6, 7, 8, 9]
>>> A[5:10]
[9, 5, 6, 7, 8]

So you can see that A[5:] = t[1] and A[5:10] = t[1] are going to have
different effects.

Cheers,
M.

-- 
  ZAPHOD:  Listen three eyes, don't try to outwierd me, I get stranger
           things than you free with my breakfast cereal.
                    -- The Hitch-Hikers Guide to the Galaxy, Episode 7



More information about the Python-list mailing list