[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)
2 0 LOAD_FAST 1 (y)
3 LOAD_FAST 0 (x)
6 ROT_TWO
7 STORE_FAST 0 (x)
10 STORE_FAST 1 (y)
13 LOAD_CONST 0 (None)
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)
2 0 LOAD_FAST 0 (x)
3 LOAD_FAST 1 (y)
6 BINARY_XOR
7 STORE_FAST 1 (y)
3 10 LOAD_FAST 0 (x)
13 LOAD_FAST 1 (y)
16 BINARY_XOR
17 STORE_FAST 0 (x)
4 20 LOAD_FAST 0 (x)
23 LOAD_FAST 1 (y)
26 BINARY_XOR
27 STORE_FAST 1 (y)
30 LOAD_CONST 0 (None)
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)
2 0 LOAD_FAST 2 (z)
3 LOAD_FAST 1 (y)
6 LOAD_FAST 0 (x)
9 ROT_THREE
10 ROT_TWO
11 STORE_FAST 0 (x)
14 STORE_FAST 1 (y)
17 STORE_FAST 2 (z)
20 LOAD_CONST 0 (None)
23 RETURN_VALUE
I wonder why it doesn't just load them in the reverse order of the store
and dispense with the ROT opcodes?
Kent
More information about the Tutor
mailing list