user1767754 user1767754 - 2 months ago 30
Python Question

Python Swap in Place in a list? x[0], x[1] = x[1], x[0]

I was always creating an extra temp variable when swapping two list elements and i've realized that the code beneath works. Is python creating in memory x[1],x[0] to the right of the equal sign before it evaluates? Can someone elaborate more?

x = [1,2]
x[0], x[1] = x[1], x[0] #swap elements
print x
>>[2,1]

Answer

The right hand side is evaluated first and the result is a new tuple. The tuple is then unpacked and bound to each of the variables (elements of the list) on the left hand side.

The temporary memory used here is that required for the tuple on the RHS.

Note that the fact that the items are elements of a list is unimportant - the same will occur for "free-standing" variables.

Since you are using a list the same effect can be achieved with slices, which also creates a temporary list and unpacks it:

>>> x = [1, 2, 3, 4]
>>> x[:2] = x[1::-1]
>>> x
[2, 1, 3, 4]
Comments