No swap function in Python?

Bernhard Herzog bh at
Wed May 30 11:46:52 EDT 2001

Pierre Barn <pbarn at> writes:

> in article 3B150A65.5D4986FC at, Bolton, Gawain
> [ADC:4808:EXCH] at boltong at wrote on 30/05/01 16:57:
> > Which made me think that a swap could be done like this:
> > 
> > (a,b) = (b,a)
> You can do a, b = b, a
> As you discovered.
> > is this an efficient
> > way of doing a swap?
> It is

Well, if a and b are local variables, the more traditional idiom
temp = a; a = b; b = temp
is a tad faster, at least on my machine, because a, b = b, a actually
constructs the intermediate tuple object.

Of course, a, b = b, a is much easier to read, which outweighs the
minuscule speed advantage of the other form.


Intevation GmbH                       

More information about the Python-list mailing list