No swap function in Python? 
Author Message
 No swap function in Python?

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?

Thanx in advance,

Gawain

--
-------------------------------------------------------------------------------

Section 4808                      | Internal mail stop: BA54
UMTS Development                  |
Nortel Networks                   | Voice:  ESN 579-3763   +33 1.39.44.37.63
Guyancourt, France                | FAX:    ESN 579-3009   +33 1.39.44.30.09
-------------------------------------------------------------------------------



Sun, 16 Nov 2003 22:57:41 GMT  
 No swap function in Python?


Quote:
> 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.

Quote:
> is this an efficient
> way of doing a swap?

It is
--
Regards,
Francois Granger



Sun, 16 Nov 2003 23:35:41 GMT  
 No swap function in Python?

Quote:



> > 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/



Sun, 16 Nov 2003 23:46:52 GMT  
 No swap function in Python?

Quote:

> (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 fine. This is called tuple packing (and unpacking). See here <> for
details.

Cheers,
Simon Brunning
TriSystems Ltd.

-----------------------------------------------------------------------
The information in this email is confidential and may be legally privileged.
It is intended solely for the addressee. Access to this email by anyone else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in
reliance on it, is prohibited and may be unlawful. TriSystems Ltd. cannot
accept liability for statements made which are clearly the senders own.



Sun, 16 Nov 2003 23:24:11 GMT  
 No swap function in Python?
| 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



Sun, 16 Nov 2003 23:30:07 GMT  
 No swap function in Python?

Quote:

> There doesn't seem to be a "swap" function in Python two swap the values
> of two variables.   I was wondering why this is.

Because it isn't necessary.

Quote:
> 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.

It is.

Quote:
> 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?

Yes.

--

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!



Sun, 16 Nov 2003 23:33:28 GMT  
 No swap function in Python?

    >> Finally, if the behaviour is guaranteed, is this an efficient way of
    >> doing a swap?

    Thomas> Yes.

Relatively speaking, yes it is efficient.  Still, you do wind up creating
and deleting a tuple as a result, which while not terribly expensive is not
without cost.  "(a,b) = (b,a)" compiles to (approximately):

    LOAD_FAST           b
    LOAD_FAST           a
    BUILD_TUPLE         2
    UNPACK_TUPLE        2
    STORE_FAST          a
    STORE_FAST          b

It's easy to see how you can use the runtime stack without going through the
BUILD/UNPACK pair:

    LOAD_FAST           b
    LOAD_FAST           a
    STORE_FAST          b
    STORE_FAST          a

Any peephole optimizer can do this for you... ;-)

Skip



Mon, 17 Nov 2003 00:00:39 GMT  
 No swap function in Python?

Quote:


> > There doesn't seem to be a "swap" function in Python two swap the values
> > of two variables.   I was wondering why this is.

> Because it isn't necessary.

Or possible, in any helpful sense of the word.

Cheers,
M.

--
  You have run into the classic Dmachine problem: your machine has
  become occupied by a malevolent spirit.  Replacing hardware or
  software will not fix this - you need an exorcist.
                                       -- Tim Bradshaw, comp.lang.lisp



Mon, 17 Nov 2003 01:10:09 GMT  
 No swap function in Python?
On Wed, 30 May 2001 16:57:41 +0200, Bolton, Gawain [ADC:4808:EXCH]
[snip]

Quote:
>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.

It is safe and idiomatic. This is the canonical way of swapping the bindings of
variables.

Quote:
>Finally, if the behaviour is guaranteed, is this an efficient
>way of doing a swap?

Efficient of what? Read the Camel book. :->

This is the simplest way to represent the operation and therefore the most
efficient use of author, maintainer, and porter time (the most scarce
resource).

--



Mon, 17 Nov 2003 06:17:56 GMT  
 No swap function in Python?
"(a,b) = (b,a)" compiles to (approximately):

Quote:

>     LOAD_FAST b
>     LOAD_FAST a
>     BUILD_TUPLE 2
>     UNPACK_TUPLE 2
>     STORE_FAST a
>     STORE_FAST b

> It's easy to see how you can use the runtime stack without going through
the
> BUILD/UNPACK pair:

>     LOAD_FAST b
>     LOAD_FAST a
>     STORE_FAST b
>     STORE_FAST a

> Any peephole optimizer can do this for you... ;-)

> Skip

..that looks a lot faster than the 'normal' way!
(maybe there should be a built-in operator or something to do exactly that)

..what is a peephole optimizer? and where can I get one?



Mon, 17 Nov 2003 08:16:49 GMT  
 No swap function in Python?

    [ snipped example of eliding BUILD_TUPLE/UNPACK_TUPLE ]

    Nick> ..that looks a lot faster than the 'normal' way!  (maybe there
    Nick> should be a built-in operator or something to do exactly that)

    Nick> ..what is a peephole optimizer? and where can I get one?

You might poke around looking for Michael Hudson's (I think he's the author)
byte code hacks package.  The freeze/xfreeze family also uses some peephole
optimization techniques.  I wrote a demonstration peephole optimizer which I
mentioned in a post earlier today.  If you're anxious to dive into it (it's
nearly three years old and was written for Python 1.5.1), I just remembered
it's available from

    http://musi-cal.mojam.com/~skip/python/

(search for "peephole").  An HTML version of the paper I presented at SPAM-7
is also there.

A peephole optimizer is generally a last-ditch effort at reorganizing code
(often, the assembly code generated by an earlier pass of the compiler) by
only considering patterns that extend over a relatively small string of
opcodes.  If you think of watching a construction site through a knothole in
a fence, you'll get the idea.  You only see a little bit of the whole
program at once.  In the absence of other optimization techniques you can
sometimes get significant speedups on fairly specific bits of code, but
peephole optimization techniques tend to generally yield only modest
benefits.

--

(847)971-7098



Mon, 17 Nov 2003 11:18:39 GMT  
 No swap function in Python?


Quote:

>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.  

It is safe, with one caveat: it *looks* thread-safe, but it may not be.
However, if you're not writing threaded applications, you don't have to
worry about that in the slightest.
--

Androgynous poly {*filter*} vanilla {*filter*} het Pythonista   http://www.*-*-*.com/
Hugs and backrubs -- I break Rule 6

"Characters exist to suffer, you know.  An author needs a little {*filter*}
in her makeup."  --Brenda Clough



Mon, 17 Nov 2003 13:09:03 GMT  
 No swap function in Python?

Quote:

> "(a,b) = (b,a)" compiles to (approximately):

> >     LOAD_FAST b
> >     LOAD_FAST a
> >     BUILD_TUPLE 2
> >     UNPACK_TUPLE 2
> >     STORE_FAST a
> >     STORE_FAST b

> > It's easy to see how you can use the runtime stack without going through
> the
> > BUILD/UNPACK pair:

> >     LOAD_FAST b
> >     LOAD_FAST a
> >     STORE_FAST b
> >     STORE_FAST a

> > Any peephole optimizer can do this for you... ;-)

> > Skip

> ..that looks a lot faster than the 'normal' way!
> (maybe there should be a built-in operator or something to do exactly that)

Firstly, thanks to everyone for their replies to this "trivial" question!

This is why I think it might be an idea to have a "swap" function in Python.
Besides making for more readable code - ok ok, I have not done a survey and
have no statistical or theoretical data to support this claim but let's
pretend humans understand words more readily than symbolic notation - a swap
function could generate the optimized code without any need for peephole
optimization.

Furthermore, as Aahz Maruch alludes to in another follow-up post, an "atomic"
swap might also be useful when writing multi-threaded applications.

That's my 2 Euro cents worth (which admittedly is not a lot!).

Gawain

--
-------------------------------------------------------------------------------

Section 4808                      | Internal mail stop: BA54
UMTS Development                  |
Nortel Networks                   | Voice:  ESN 579-3763   +33 1.39.44.37.63
Guyancourt, France                | FAX:    ESN 579-3009   +33 1.39.44.30.09
-------------------------------------------------------------------------------



Mon, 17 Nov 2003 16:13:21 GMT  
 No swap function in Python?

Quote:
> This is why I think it might be an idea to have a "swap" function in Python.
> Besides making for more readable code - ok ok, I have not done a survey and
> have no statistical or theoretical data to support this claim but let's
> pretend humans understand words more readily than symbolic notation - a swap
> function could generate the optimized code without any need for peephole
> optimization.

A swap function is impossible in Python. A function cannot rebind names in
the caller's namespace. This is why del is a statement and not a function,
for instance.

--
Remco Gerlich



Tue, 18 Nov 2003 02:15:24 GMT  
 No swap function in Python?

Quote:

> "(a,b) = (b,a)" compiles to (approximately):

> >     LOAD_FAST b
> >     LOAD_FAST a
> >     BUILD_TUPLE 2
> >     UNPACK_TUPLE 2
> >     STORE_FAST a
> >     STORE_FAST b

> > It's easy to see how you can use the runtime stack without going through
> the
> > BUILD/UNPACK pair:

> >     LOAD_FAST b
> >     LOAD_FAST a
> >     STORE_FAST b
> >     STORE_FAST a

> > Any peephole optimizer can do this for you... ;-)

> > Skip

> ..that looks a lot faster than the 'normal' way!
> (maybe there should be a built-in operator or something to do exactly that)

Firstly, thanks to everyone for their replies to this "trivial" question!

This is why I think it might be an idea to have a "swap" function in Python.
Besides making for more readable code - ok ok, I have not done a survey and
have no statistical or theoretical data to support this claim but let's
pretend humans understand words more readily than symbolic notation - a swap
function could generate the optimized code without any need for peephole
optimization.

Furthermore, as Aahz Maruch alludes to in another follow-up post, an "atomic"
swap might also be useful when writing multi-threaded applications.

That's my 2 Euro cents worth (which admittedly is not a lot!).

Gawain

--
-------------------------------------------------------------------------------

Section 4808                      | Internal mail stop: BA54
UMTS Development                  |
Nortel Networks                   | Voice:  ESN 579-3763   +33 1.39.44.37.63
Guyancourt, France                | FAX:    ESN 579-3009   +33 1.39.44.30.09
-------------------------------------------------------------------------------



Mon, 17 Nov 2003 16:13:21 GMT  
 
 [ 29 post ]  Go to page: [1] [2]

 Relevant Pages 

1. Is there swap function in Python?

2. Swapping values [XOR][SWAP]

3. problem with a function swap

4. A Swap Function

5. swap val function

6. Scope troubles with a swap function

7. swap function?

8. Python Windll - passing python lists to DLL function using Windll

9. VC++ calling fortran function and fortran function calling a c++ function

10. Calling functions from functions from functions ...

11. Sorting Functions in a Python Program

12. function memoizer in Python

 

 
Powered by phpBB® Forum Software