Peculiar swap behavior
andrew cooke
andrew at acooke.org
Tue Feb 24 00:41:55 CET 2009
andrew cooke wrote:
> 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?
To answer my own question - you can rewrite all cases to use rhs1, rhs2.
The point is that when you do that: one case (m, n = n, m) reassigns
variables; one case (m[:], n[:] = n, m) mutates one list to be equal to
the other; one case (m[:], n[:] = n[:], m[:]) avoids seeing the effects of
the mutation because a copy is generated.
Which is what other people said, I guess.
Andrew
More information about the Python-list
mailing list