Peculiar swap behavior

Delaney, Timothy (Tim) tdelaney at avaya.com
Mon Feb 23 15:34:57 EST 2009


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])
> 
> 
> 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? :)

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

After the third line, m == n, giving the behaviour you see. 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

Tim Delaney



More information about the Python-list mailing list