# [Tutor] Variable Swap

Kent Johnson kent37 at tds.net
Tue Jan 30 13:47:40 CET 2007

```Steve Nelson wrote:
>> x, y = y, x
>
> Doesn't this use temporary variables?

Yes, behind the scenes maybe it does. It may create a temporary list,
then unpack it - that is what the syntax actually means. Let's take a look:

In [1]: import dis

In [2]: def f(x, y):
...:     x, y = y, x
...:
...:

In [3]: dis.dis(f)
6 ROT_TWO
7 STORE_FAST               0 (x)
10 STORE_FAST               1 (y)
16 RETURN_VALUE

So it is actually using the stack to store the variables. In a sense it
is a temporary but it is not using an actual variable location and it is
pretty efficient; much more so than your xor trick:

In [6]: def h(x, y):
...:     y=x^y
...:     x=x^y
...:     y=x^y
...:
...:

In [7]: dis.dis(h)
6 BINARY_XOR
7 STORE_FAST               1 (y)

16 BINARY_XOR
17 STORE_FAST               0 (x)

26 BINARY_XOR
27 STORE_FAST               1 (y)
33 RETURN_VALUE

Surprisingly, the stack optimization even works with three variables:
In [4]: def g(x, y, z):
...:     x, y, z = z, y, x
...:
...:

In [5]: dis.dis(g)
9 ROT_THREE
10 ROT_TWO
11 STORE_FAST               0 (x)
14 STORE_FAST               1 (y)
17 STORE_FAST               2 (z)