Peculiar swap behavior

John Posner jjposner at snet.net
Tue Feb 24 01:58:44 CET 2009


>>      m,n = [1,2,3],[4,5,6]
>>      m[:],n[:] = n,m

I believe this is an RTFM situation. In the Python 2.6.1 help topic "Simple Statements" > "Assignment Statements", see this para:
<snip>
If the target is a slicing: The primary expression in the reference is evaluated. It should yield a mutable sequence object (such as a list). The assigned object should be a sequence object of the same type. Next, the lower and upper bound expressions are evaluated, insofar they are present; defaults are zero and the sequence’s length. The bounds should evaluate to (small) integers. If either bound is negative, the sequence’s length is added to it. The resulting bounds are clipped to lie between zero and the sequence’s length, inclusive. Finally, the sequence object is asked to replace the slice with the items of the assigned sequence. The length of the slice may be different from the length of the assigned sequence, thus changing the length of the target sequence, if the object allows it.
</snip>
The crucial sentence is:
     Finally, the sequence object is asked to replace the slice with the items
     of the assigned sequence.
In our example, this means that the assignment of the 3-item slicing
    m[:] = n
... has this result:
 * the identifier m[0] now refers to the same object as the identifier n[0]
 * the identifier m[1] now refers to the same object as the identifier n[1]
 * the identifier m[2] now refers to the same object as the identifier n[2]
Although m and n are still different list objects, all of the "slots" in both lists now contain the same (sub)objects.
I've verified the above analysis to my own satisfaction using IDLE 2.6.1:
---------
def list_ids(mylist):
    return id(mylist), map(id, mylist)
    
m,n = [1,2,3],[4,5,6]
print m,n

print "m:", list_ids(m)
print "n:", list_ids(n)

m[:], n[:] = n, m
print m,n

print "m:", list_ids(m)
print "n:", list_ids(n)
---------

output:

[1, 2, 3] [4, 5, 6]
m: (4589728, [10970688, 10970676, 10970664])
n: (11311344, [10970652, 10970640, 10970628])
[4, 5, 6] [4, 5, 6]
m: (4589728, [10970652, 10970640, 10970628])
n: (11311344, [10970652, 10970640, 10970628])


-John
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090223/422b7ea3/attachment.html>


More information about the Python-list mailing list