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]
user1767754
  • 23,311
  • 18
  • 141
  • 164

2 Answers2

1

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]
mhawke
  • 84,695
  • 9
  • 117
  • 138
1

Maybe this illustrates better what happens:

>>> a = 1, 2
>>> a
(1, 2)
>>> type(a)
<type 'tuple'>

As you can see the RHS is "wrapped" in a tuple and then assigned to a.

Now let's look at another example, a "destructuring" assignment:

>>> t = (1, 2)
>>> a, b = t
>>> a
1
>>> b
2

Now if you combine the two you should understand what's going on in the example you posted.

Michael Kohl
  • 66,324
  • 14
  • 138
  • 158