Peculiar swap behavior

Robert Kern robert.kern at gmail.com
Mon Feb 23 18:00:50 EST 2009

```On 2009-02-23 16:17, 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?

n[:] on the RHS makes a copy of the list.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma