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,x to the right of the equal sign before it evaluates? Can someone elaborate more?
x = [1,2]
x, x = x, x #swap elements
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]