Peculiar swap behavior

T

Tim Chase

I stumbled across this oddity and was hoping folks on the list
might be able to provide a little understanding:

# swap scalars(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:

or even just

but not

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

Thanks,

-tkc
 
A

Aaron Brady

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])
snip

This may help:
a= [1,2,3]
id(a) 12170584
id(a[:])
12235520

However, I'm not thinking in English at the moment.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,040
Latest member
papereejit

Latest Threads

Top