Peculiar swap behavior

Tim Chase python.list at tim.thechases.com
Mon Feb 23 13:43:44 EST 2009


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 abstraction.  It seems to work if I force content-copying:

 >>> m[:],n[:] = n[:],m[:]

or even just

 >>> m[:],n[:] = n,m[:]

but not

 >>> m[:],n[:] = n[:],m

Is this a bug, something Python should smack the programmer for 
trying, or just me pushing the wrong edges? :)

Thanks,

-tkc








More information about the Python-list mailing list