11.3. Tuple Assignment¶
One of the unique syntactic features of Python is the ability to have a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time when the left side is a sequence.
In this example we have a two-element list (which is a sequence) and
assign the first and second elements of the sequence to the variables
y in a single statement.
This isn’t magic! Python roughly translates the tuple assignment syntax to the following:
It’s worth noting that Python does not translate the syntax literally. For example, if you try this with a dictionary, it won’t work as you might expect.
Stylistically, when we use a tuple on the left side of the assignment statement, we omit the parentheses, but the following is an equally valid syntax:
A particularly clever application of tuple assignment allows us to swap the values of two variables in a single statement:
>>> a, b = b, a
Both sides of this statement are tuples, but Python interprets the left side to be a tuple of
variables and the right side to be a tuple of expressions. All of
the expressions on the right side are evaluated before any of the
assignments. This means that the values of
a on the right side are evaluated,
b on the left side take on their values.
The number of variables on the left and the number of values on the right must be the same:
>>> a, b = 1, 2, 3 ValueError: too many values to unpack
Write code to swap the values of tuple t.
More generally, the right side can be any kind of sequence (string, list, or tuple). For example, to split an email address into a username and a domain, you could write:
>>> addr = 'email@example.com' >>> uname, domain = addr.split('@')
The return value from
split() is a list with two elements;
the first element is assigned to
uname, the second to
>>> print(uname) monty >>> print(domain) python.org