I l@ve RuBoard Previous Section Next Section

1.2 Swapping Values WithoutUsing a Temporary Variable

Credit: Hamish Lawson

1.2.1 Problem

You want to swap the values of some variables, but you don't want to use a temporary variable.

1.2.2 Solution

Python's automatic tuple packing and unpacking make this a snap:

a, b, c = b, c, a

1.2.3 Discussion

Most programming languages make you use temporary intermediate variables to swap variable values:

temp = a
a = b
b = c
c = temp

But Python lets you use tuple packing and unpacking to do a direct assignment:

a, b, c = b, c, a

In an assignment, Python requires an expression on the righthand side of the =. What we wrote there�b, c, a�is indeed an expression. Specifically, it is a tuple, which is an immutable sequence of three values. Tuples are often surrounded with parentheses, as in (b, c, a), but the parentheses are not necessary, except where the commas would otherwise have some other meaning (e.g., in a function call). The commas are what create a tuple, by packing the values that are the tuple's items.

On the lefthand side of the = in an assignment statement, you normally use a single target. The target can be a simple identifier (also known as a variable), an indexing (such as alist[i] or adict['freep']), an attribute reference (such as anobject.someattribute), and so on. However, Python also lets you use several targets (variables, indexings, etc.), separated by commas, on an assignment's lefthand side. Such a multiple assignment is also called an unpacking assignment. When there are two or more comma-separated targets on the lefthand side of an assignment, the value of the righthand side must be a sequence of as many items as there are comma-separated targets on the lefthand side. Each item of the sequence is assigned to the corresponding target, in order, from left to right.

In this recipe, we have three comma-separated targets on the lefthand side, so we need a three-item sequence on the righthand side, the three-item tuple that the packing built. The first target (variable a) gets the value of the first item (which used to be the value of variable b), the second target (b) gets the value of the second item (which used to be the value of c), and the third and last target (c) gets the value of the third and last item (which used to be the value of a). The net result is a swapping of values between the variables (equivalently, you could visualize this particular example as a rotation).

Tuple packing, done using commas, and sequence unpacking, done by placing several comma-separated targets on the lefthand side of a statement, are both useful, simple, general mechanisms. By combining them, you can simply, elegantly, and naturally express any permutation of values among a set of variables.

1.2.4 See Also

The Reference Manual section on assignment statements.

    I l@ve RuBoard Previous Section Next Section