Peculiar swap behavior

andrew cooke andrew at acooke.org
Mon Feb 23 17:17:42 EST 2009


Delaney, Timothy (Tim) wrote:
> Tim Chase wrote:
>> # 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])
[...]
> For these types of things, it's best to expand the code out. The
> appropriate expansion of:
>     m,n = [1,2,3],[4,5,6]
>     m[:],n[:] = n,m
> is:
>     m = [1,2,3]
>     n = [4,5,6]
>     m[:] = n
>     n[:] = m
> [...] OTOH, for:
>     m,n = [1,2,3],[4,5,6]
>     m[:],n[:] = n[:],m[:]
> the expansion is more like:
>     m = [1,2,3]
>     n = [4,5,6]
>     rhs1 = n[:]
>     rhs2 = m[:]
>     m[:] = rhs1
>     n[:] = rhs2

Maybe I'm just being stupid, but you don't seem to have explained
anything.  Isn't the question: Why is the expansion different for the two
cases?  Why don't both expand to have the intermediate rhs variables?

Andrew





More information about the Python-list mailing list