# 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)
6 ROT_TWO
7 STORE_NAME               1 (x)
10 STORE_NAME               0 (y)
16 RETURN_VALUE

>>> dis.dis(transpose)
3 PRINT_ITEM
7 PRINT_ITEM
11 PRINT_ITEM

19 STORE_FAST               0 (x)

28 BINARY_SUBTRACT
29 STORE_FAST               1 (y)

38 BINARY_SUBTRACT
39 STORE_FAST               0 (x)

45 PRINT_ITEM
49 PRINT_ITEM
53 PRINT_ITEM
54 PRINT_NEWLINE
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

```