Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata