Swapping values of two variables

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Thu Jan 29 22:07:55 EST 2009


On Thu, 29 Jan 2009 16:29:11 -0800, Eric Kang 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

Yes.


> 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?

Ints in Python are *objects*, not 32-bit quantities. An int is 12 bytes 
(96 bits) in size; a long will use as much memory as needed. If your 
application needs to optimize a swap of two ints, then Python is probably 
going to be much too memory-intensive for you.

(But my money is on you doing premature optimization.)



-- 
Steven



More information about the Python-list mailing list