No swap function in Python?

D-Man dsh8290 at rit.edu
Wed May 30 11:30:07 EDT 2001


On Wed, May 30, 2001 at 04:57:41PM +0200, Bolton, Gawain [ADC:4808:EXCH] wrote:
| There doesn't seem to be a "swap" function in Python two swap the values
| of two variables.   I was wondering why this is.
| 
| Unfortunately writing a generic swap function swap(a,b) with no return
| type in Python doesn't work with immutable arguments (like strings) of
| course.  Which made me think that a swap could be done like this:
| 
| (a,b) = (b,a)
| 
| But I'm not completely convinced doing this is safe.  In tests I've done
| it works, but I'm not sure whether this works in all cases with all
| types...  Finally, if the behaviour is guaranteed, is this an efficient
| way of doing a swap?

This is the way it is done in Python.  What it does is create a tuple
containing b and a (the right-hand-side of the statement) then unpack
it into the tuple on the left-hand-side (containing a and b
respectively). 

It works with all types because tuples are heterogeneouse containers
and don't care what type of object it contains.  It is entirely up to
your client code what you want to do with the tuple and the objects
contained in it.  It is your client code that you must ensure the
types make sense for the operations it wants to perform on it.  This
is really not a problem because of Python's strong dynamic typing
mechanism, and has nothing to do with swapping techniques.

Another solution, if you really don't like tuple packing and
unpacking, is :

temp = b
b = a 
a = temp
del temp

but I think it is obvious that this technique consists of 3 (4)
statements instead of just one and the creation and deletion of a new
variable.  My guess is that the tuple technique is more efficient as
well as being more concise, but you would need to profile it to be
sure.

-D





More information about the Python-list mailing list