No swap function in Python?
Bernhard Herzog
bh at intevation.de
Wed May 30 11:46:52 EDT 2001
Pierre Barn <pbarn at altern.org> writes:
> in article 3B150A65.5D4986FC at europem01.nt.com, Bolton, Gawain
> [ADC:4808:EXCH] at boltong at europem01.nt.com 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.
Bernhard
--
Intevation GmbH http://intevation.de/
Sketch http://sketch.sourceforge.net/
MapIt! http://mapit.de/
More information about the Python-list
mailing list