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.

One thought on “Swapping variables without a temporary”

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.