Swapping values of two variables

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Fri Jan 30 01:32:37 EST 2009


On Thu, 29 Jan 2009 21:23:48 -0800, Kottiyath wrote:

> Is it possible to swap two floats without a variable?

In Python? Sure.

f = 1.23
g = 2.87
f, g = g, f



This idiom is independent of the types of the objects:

x = "hello world"
y = [1, 2.0, None, "xyz", {}]
x, y = y, x

In other languages? Hard to say. You *might* be able to use the XOR trick 
on floats, if you can access a float as a set of raw bytes. Same for 
strings, if they are the same length.

Assuming that the floats are of similar size, not NaNs or INFs, not 
subject to overflow or underflow, and not subject to rounding error, you 
can do this trick:

>>> f = 1.23
>>> g = 2.87
>>> f, g
(1.23, 2.8700000000000001)
>>> 
>>> f = f + g
>>> g = f - g
>>> f = f - g
>>> f, g
(2.8700000000000001, 1.2299999999999995)

But notice the round-off error in g. It gets worse if your values are of 
radically different sizes:


>>> f = 123.4
>>> g = 1.2e35
>>> f, g
(123.40000000000001, 1.2000000000000001e+35)
>>> f = f + g
>>> g = f - g
>>> f = f - g
>>> f, g
(1.2000000000000001e+35, 0.0)


This really is a trick, not something you should be doing in production 
code.



-- 
Steven



More information about the Python-list mailing list