cpbotha.net

voices in my head

cpbotha.net random header image

Swapping variables without a temporary

June 19th, 2003 · 1 Comment · Uncategorized

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. The Commonly Confused Words Test
  2. Uptime schmuptime
  3. A new machine
  4. envedit Windows Environment Editor released
  5. New release of envedit

Tags:

One Comment so far ↓

Leave a Comment