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. Uptime schmuptime
  2. Facebook Like, Share and Retweet buttons in your WordPress
  3. A new machine
  4. New new laptop laptop!!
  5. Emacs Python folding fixed

Tags:

One Comment so far ↓

Leave a Comment