# Swapping values of two variables

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Fri Jan 30 04:31:03 CET 2009

```On Thu, 29 Jan 2009 17:50:04 -0800, tony.clarke5 wrote:

> On Jan 30, 12:29 am, Eric Kang <y... at sfu.ca> wrote:
>> In python, I set:
>>
>> x=1
>> y=3
>>
>> z = x
>> x = y
>> y = z
>>
>> This gave me 3 1, which are the values of x and y swapped. The
>> following would have given me the same result: x, y = y, x
>>
>> But could the swapping be done using less extra memory than this? What
>> is the minimum amount of extra memory required to exchange two 32-bit
>> quantities? What would be the pseudocode that achieves this minimum?
>
> def transpose(x, y):
>     print x, y, 'becomes: ',
>     x = x + y
>     y = x - y
>     x = x - y
>     print x, ' ', y
>
> transpose(1,3)
> transpose (9,8)

I'm not sure what the point of that function is. It doesn't actually swap
its arguments:

>>> x = 23
>>> y = 42
>>> transpose(x, y)
23 42 becomes:  42   23
>>> x
23
>>> y
42

And it certainly doesn't save memory, as the original poster asked:

>>> import dis
>>> swap = compile('x, y = y, x', '', 'single')
>>> dis.dis(swap)
1           0 LOAD_NAME                0 (y)
3 LOAD_NAME                1 (x)
6 ROT_TWO
7 STORE_NAME               1 (x)
10 STORE_NAME               0 (y)
13 LOAD_CONST               0 (None)
16 RETURN_VALUE

>>> dis.dis(transpose)
2           0 LOAD_FAST                0 (x)
3 PRINT_ITEM
4 LOAD_FAST                1 (y)
7 PRINT_ITEM
8 LOAD_CONST               1 ('becomes: ')
11 PRINT_ITEM

3          12 LOAD_FAST                0 (x)
15 LOAD_FAST                1 (y)
19 STORE_FAST               0 (x)

4          22 LOAD_FAST                0 (x)
25 LOAD_FAST                1 (y)
28 BINARY_SUBTRACT
29 STORE_FAST               1 (y)

5          32 LOAD_FAST                0 (x)
35 LOAD_FAST                1 (y)
38 BINARY_SUBTRACT
39 STORE_FAST               0 (x)

6          42 LOAD_FAST                0 (x)
45 PRINT_ITEM
46 LOAD_CONST               2 (' ')
49 PRINT_ITEM
50 LOAD_FAST                1 (y)
53 PRINT_ITEM
54 PRINT_NEWLINE
55 LOAD_CONST               0 (None)
58 RETURN_VALUE

The compiled code of the transpose function *alone* (not including all
the other associated parts) takes 59 bytes, or 472 bits.

>>> len(transpose.func_code.co_code)
59

Even if it worked, that's hardly using less memory than a direct swap.

--
Steven

```