Search code examples
pythonvariablesswap

Swapping variables and list elements in Python works unexpectedly


I have just came up with an example of code:

ls = [2222, 1111]

a = ls[0]
print(a is ls[0])

a, ls[1] = ls[1], a
print(ls)

which prints:

True
[2222, 2222]

My question is, why isn't a the same object as ls[0] in the above case? The a is ls[0] check is True, therefore it must be the same as:

ls[0], ls[1] = ls[1], ls[0]

but it isn't. The latter one produces [1111, 2222]. What is this mYsTeRy?


Solution

  • Simple assignments have no affect on the previous value of the target.

    After

    ls = [2222, 1111]
    
    a = ls[0]
    

    both a and the first element of ls are references to the integer 2222.

    The assignment

    a, ls[1] = ls[1], a
    

    is effectively the same as

    t = ls[1], a  # The tuple (1111, 2222)
    a = t[0]  # Set a to t[0] == 1111
    ls[1] = t[1]  # Set ls[1] to t[1] == 2222
    

    At no point have you modified the first element of ls; you've only changed what a refers to and what the second element of ls refers to. You can see that a is now refers to 1111, since that's what the value of ls[1] was before ls[1] was modified.

    >>> print(a)
    1111