Swapping variables without a temporary

This is from the first recipe in my brand-new Python cookbook. It’s quite obvious, but it hasn’t really struck me before. Well doh.

In most languages, swapping the values in two variables means using an intermediate temporary variable, e.g.:

int a = 1;
int b = 2;
int temp;
temp = a;
a = b;
b = temp;

With the tuple packing and unpacking in Python however, we don’t need no steenking temporary variables!

a = 1
b = 2
b, a = a, b

Obviously this principle scales to any number of variables, e.g.:

a, b, c, d = d, c, b, a

*sniff* That’s just so sweet.

Related posts:

  1. Uptime schmuptime
  2. A new machine
  3. Emacs Python folding fixed
  4. Python new-style object method resolution order
  5. Lush, OCaml and more, part deux

One Response to Swapping variables without a temporary

  1. Paul just pointed me here:
    http://www.devx.com/getHelpOn/Article/11395/0/page/2
    It’s explained how to swap variables without a temporary in C as well.

    It’s ugly though. :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>