slicing and parallel assignment: inconsistent behaviour??
Chris Liechti
cliechti at gmx.net
Thu Jul 18 05:38:15 EDT 2002
tjd at sfu.ca (Toby Donaldson) wrote in
news:ad32251c.0207172302.12f4ef4f at posting.google.com:
> 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?
hint: the first part is 5 elements, the second 4
>>> F = range(10)
>>> F[5:], F[1:5]
([5, 6, 7, 8, 9], [1, 2, 3, 4])
and
>>> D = range(10)
>>> D[1:5], D[5:] = ['a'], ['b']
>>> D
[0, 'a', 5, 6, 7, 'b']
>>> D = range(10)
>>> D[1:5], D[5:10] = ['a'], ['b']
>>> D
[0, 'a', 5, 6, 7, 'b']
>>>
using [5:10] or [5:] has the same effect here, but you can see that
D[1:5] replaces 4 elements with 'a', and _afterwards_ it replaces [5:] (or
[5:10] which is the same here: a list of 2 elements: [8,9] ) with 'b'.
an now to your situation. lets do it step by step:
>>> D = range(10)
>>> D[1:5] = [5, 6, 7, 8, 9]
>>> D
[0, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9]
ya see: 11 elements and hece : or :10 _makes_ a difference:
>>> D[5:]
[9, 5, 6, 7, 8, 9]
>>> D[5:10]
[9, 5, 6, 7, 8]
i think your first example isn't realy doing what you expect it only has
all the numbers in it you would expect ;-)
HTH
chris
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list