Is there swap function in Python?

Chad Netzer cnetzer at mail.arc.nasa.gov
Sun Apr 6 23:19:24 CEST 2003


On Sun, 2003-04-06 at 13:16, Xin Liu wrote:
> >
> > What do you mean by the swap function? What should it do
> > precisely?
> >
> > -- 
> > René Pijlman
> It is a function like swap(a, b) . Use to swap the value of a and b.

Python doesn't work this way.  Python references refer to an object. 
You can swap references, but you can't (in general) swap the memory
contents of objects.  Nor do you need to or want to.

In C++ it makes sense to talk about swapping the "value of a and b".  In
Python, the value of a and b would not change, but the labels in the
current namespace (ie. a and b) can be swapped.  The objects themselves
would remain the same.

So rather than calling a functions swap(a, b), you just do a,b = b,a

In general, python functions do not mess with their caller's namespace,
so it could not operate like the C++ swap() with references.

So, this makes sense in Python:

a = 1
b = 2

def swap(t1, t2):
    return t2, t1

a,b = swap(a, b)   # After this point, a == 2 and b == 1


But there is not way (other than abusing globals or the module
namespace) to do it like this:

a = 1
b = 2

def swap(t1, t2):
    t2, t1 = t1, t2
    return

swap(a, b)
# After this point, a == 1 and b == 2.  The calling namespace is
# not changed.


Using classes, you can create namespaces that can be manipulated by
callable objects (the class instance's methods), and in that case, it
*may* be meaningful to have a swap() method.  But still, it is only
manipulating a namespace within which the objects are referred to, not
the swapped objects themselves (or their contents in machine memory). 
The below is illustrative only, not meant to be used for a practical
use:


class Pair:
    def __init__(self, t1, t2):
        self.t1 = t1
        self.t2 = t2

    def get(self):
        return self.t1, self.t2

    def swap(self):
        self.t1, self.t2 = self.t2, self.t1


a = 1
b = 2
pair = Pair(a, b)
pair.get()   # returns 1,2
pair.swap()  # changes the namespace of the pair object
pair.get()   # returns 2,1

a == 1
b == 2       # The a and b labels did NOT change


-- 
Bay Area Python Interest Group - http://www.baypiggies.net/

Chad Netzer
(any opinion expressed is my own and not NASA's or my employer's)







More information about the Python-list mailing list