Tuples and Unpacking

A tuple holds values in order, like a list. But you cannot change a tuple after you create it. You usually write a tuple with parentheses, like (640, 480).

Unpacking puts each value of a tuple into its own variable.

size = (640, 480)
width, height = size

days = ["Mon", "Tue"]
sales = [12, 15]

print(width, height)
for day, count in zip(days, sales):
    print(f"{day}: {count}")

width, height = height, width
print(width, height)

Output:

640 480
Mon: 12
Tue: 15
480 640

width, height = size sets width to 640 and height to 480.

zip pairs up the values of two lists by position. The first value in days goes with the first value in sales, and so on. Each pair is a tuple, and the loop unpacks it into day and count.

The last two lines swap the values of width and height. Python first builds a tuple from the right side, height, width. Then it unpacks that tuple into the names on the left. So you do not need an extra variable to hold one value during the swap.

Swap the numbers and pair each name with an age in the exercise.