13.3 Tuple Assignment with Unpacking

From Foundations of Python ProgrammingGNU FDL 1.3Original pagePython1 class period4 exercises5 graded tests

README.md

13.3 Tuple Assignment with Unpacking

Python has a very powerful tuple assignment feature that allows a tuple of variable names on the left of an assignment statement to be assigned values from a tuple on the right of the assignment. Another way to think of this is that the tuple of values is unpacked into the variable names.

julia = "Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia"

name, surname, birth_year, movie, movie_year, profession, birth_place = julia

This does the equivalent of seven assignment statements, all on one easy line.

Naturally, the number of variables on the left and the number of values on the right have to be the same.

(a, b, c, d) = (1, 2, 3) # ValueError: need more than 3 values to unpack

Note

Unpacking into multiple variable names also works with lists, or any other sequence type, as long as there is exactly one value for each variable. For example, you can write x, y = [3, 4].

Swapping Values between Variables

This feature is used to enable swapping the values of two variables. With conventional assignment statements, we have to use a temporary variable. For example, to swap a and b:

a = 1
b = 2
temp = a
a = b
b = temp
print(a, b, temp)

Tuple assignment solves this problem neatly:

a = 1
b = 2
(a, b) = (b, a)
print(a, b)

The left side is a tuple of variables; the right side is a tuple of values. Each value is assigned to its respective variable. All the expressions on the right side are evaluated before any of the assignments. This feature makes tuple assignment quite versatile.

Unpacking Into Iterator Variables

Multiple assignment with unpacking is particularly useful when you iterate through a list of tuples. You can unpack each tuple into several loop variables. For example:

authors = [('Paul', 'Resnick'), ('Brad', 'Miller'), ('Lauren', 'Murphy')]
for first_name, last_name in authors:
    print("first name:", first_name, "last name:", last_name)

On the first iteration the tuple ('Paul', 'Resnick') is unpacked into the two variables first_name and last_name. One the second iteration, the next tuple is unpacked into those same loop variables.

The Pythonic Way to Enumerate Items in a Sequence

When we first introduced the for loop, we provided an example of how to iterate through the indexes of a sequence, and thus enumerate the items and their positions in the sequence.

fruits = ['apple', 'pear', 'apricot', 'cherry', 'peach']
for n in range(len(fruits)):
    print(n, fruits[n])

We are now prepared to understand a more pythonic approach to enumerating items in a sequence. Python provides a built-in function enumerate. It takes a sequence as input and returns a sequence of tuples. In each tuple, the first element is an integer and the second is an item from the original sequence. (It actually produces an "iterable" rather than a list, but we can use it in a for loop as the sequence to iterate over.)

fruits = ['apple', 'pear', 'apricot', 'cherry', 'peach']
for item in enumerate(fruits):
    print(item[0], item[1])

The pythonic way to consume the results of enumerate, however, is to unpack the tuples while iterating through them, so that the code is easier to understand.

fruits = ['apple', 'pear', 'apricot', 'cherry', 'peach']
for idx, fruit in enumerate(fruits):
    print(idx, fruit)

Check your Understanding

Check your understanding: a multiple-choice question in the book.

Exercise 1

With only one line of code, assign the variables water, fire, electric, and grass to the values "Squirtle", "Charmander", "Pikachu", and "Bulbasaur"

Open the 01 folder and edit main.py. Run Tests checks it.

Exercise 2

With only one line of code, assign four variables, v1, v2, v3, and v4, to the following four values: 1, 2, 3, 4.

Open the 02 folder and edit main.py. Run Tests checks it.

Exercise 3

If you remember, the .items() dictionary method produces a sequence of tuples. Keeping this in mind, we have provided you a dictionary called pokemon. For every key value pair, append the key to the list p_names, and append the value to the list p_number. Do not use the .keys() or .values() methods.

Open the 03 folder and edit main.py. Run Tests checks it.

Exercise 4

The .items() method produces a sequence of key-value pair tuples. With this in mind, write code to create a list of keys from the dictionary track_medal_counts and assign the list to the variable name track_events. Do NOT use the .keys() method.

Open the 04 folder and edit main.py. Run Tests checks it.

For teachers

13.3 Tuple Assignment with Unpacking

Students read Foundations of Python Programming's “Tuple Assignment with Unpacking” in CS Room and work through its 4 Python coding exercises (4 graded).

  • Time: 1 class period
  • Tests: 5 in 4 graded exercises, set up for you when you import the lesson

Exercises

FolderGradingTests
01Autograded1
02Autograded1
03Autograded2
04Autograded1