Swapping Values WithoutUsing a Temporary Variable
Credit: Hamish Lawson
Problem
You want to swap the values of some variables, but you don’t want to use a temporary variable.
Solution
Python’s automatic tuple packing and unpacking make this a snap:
a, b, c = b, c, a
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 ...