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.

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

This does the equivalent of seven assignment statements, all on one easy line. One requirement is that the number of variables on the left must match the number of elements in the tuple.

Once in a while, it is useful to swap the values of two variables. With conventional assignment statements, we have to use a temporary variable. For example, to swap a and b:

temp = a
a = b
b = temp

Tuple assignment solves this problem neatly:

(a, b) = (b, a)

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.

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

Python even provides a way to pass a single tuple to a function and have it be unpacked for assignment to the named parameters.

If you run this, you will be get an error caused by line 7, where it says that the function add is expecting two parameters, but you’re only passing one parameter (a tuple). In line 6 you’ll see that the tuple is unpacked and 5 is bound to x, 4 to y.

Don’t worry about mastering this idea yet. But later in the course, if you come across some code that someone else has written that uses the * notation inside a parameter list, come back and look at this again.

Next Section - Unpacking Dictionary Items