Peculiar swap behavior
tjreedy at udel.edu
Thu Mar 5 04:22:06 CET 2009
Tim Chase wrote:
> I stumbled across this oddity and was hoping folks on the list might be
> able to provide a little understanding:
> # swap scalars
> >>> x,y = 1,2
> >>> x,y = y,x
> >>> x,y
> (2, 1)
> # swap lists
> >>> a,b = [1,2,3],[4,5,6]
> >>> a,b = b,a
> >>> a,b
> ([4, 5, 6], [1, 2, 3])
> # swap list contents...not so much...
> >>> m,n = [1,2,3],[4,5,6]
> >>> m[:],n[:] = n,m
> >>> m,n
> ([4, 5, 6], [4, 5, 6])
> The first two work as expected but the 3rd seems to leak some internal
This works exactly as documented. Read carefully...
An assignment statement evaluates the expression list (remember that
this can be a single expression or a comma-separated list, the latter
yielding a tuple) and assigns the single resulting object to each of the
target lists, from left to right.
If the target is a slicing: The primary expression in the reference is
evaluated. It should yield a mutable sequence object (such as a list).
The assigned object should be a sequence object of the same type. Next,
the lower and upper bound expressions are evaluated, insofar they are
present; defaults are zero and the sequence’s length. The bounds should
evaluate to integers. If either bound is negative, the sequence’s length
is added to it. The resulting bounds are clipped to lie between zero and
the sequence’s length, inclusive. ***Finally, the sequence object is
asked to replace the slice with the items of the assigned sequence.***
The length of the slice may be different from the length of the assigned
sequence, thus changing the length of the target sequence, if the object
[*** emphasis added]
and ask What is the value of m when used to replace the contents of n?
More information about the Python-list