slicing and parallel assignment: inconsistent behaviour??

Denis S. Otkidach ods at fep.ru
Thu Jul 18 05:48:55 EDT 2002


On 18 Jul 2002, Toby Donaldson wrote:

TD>     >>> B = range(10)
TD>     >>> B[1:5], B[5:10] = B[5:10], B[1:5]
TD>     >>> B
TD>     [0, 5, 6, 7, 8, 1, 2, 3, 4, 9]
TD>
TD> This works as I expect. But if I leave out the 10s in the
TD> slice
TD> indices, I get this:
TD>
TD>     >>> A = range(10)
TD>     >>> A[1:5], A[5:] = A[5:], A[1:5]
TD>     >>> A
TD>     [0, 5, 6, 7, 8, 1, 2, 3, 4]
TD>
TD> Where has the 9 gone?

I should become clear when you look how it works step-by-step:
>>> A = range(10)
>>> t1, t2 = A[5:], A[1:5]
>>> t1, t2
([5, 6, 7, 8, 9], [1, 2, 3, 4])
>>> A
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> A[1:5] = t1
>>> A
[0, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9]

The length of list is now 11!

>>> A[5:] = t2
>>> A
[0, 5, 6, 7, 8, 1, 2, 3, 4]


P.S. There is no problem when you swap two blocks with the same
length.

-- 
Denis S. Otkidach
http://www.python.ru/      [ru]
http://diveinto.python.ru/ [ru]






More information about the Python-list mailing list