runtime
35 / 250
lesson 35 Lists & Tuples · beginner

Unpack a tuple

title, year = film stores each value of a tuple under its own name. In a loop over a list of tuples, for title, year in films does the same for every record.

You'll be able to
  • Unpack a tuple into names, and swap two values with a, b = b, a
  • Loop over a list of tuples with one name per field
  • Read the ValueError raised when the number of names doesn't match
The idea

A tuple is a record: ("USW00024143", "2024-01-01", 6.7) is a station, a date and a high. Reading it as reading[0], reading[1] and reading[2] works, but the numbers say nothing about what each value means.

Unpacking gives each position a name in one line: station, date, tmax = reading. You need one name per value, in order. You already used this with enumerate (see Loops & Iteration), where for i, ch in ... unpacks a pair on every pass.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · Unpacking one reading, and swapping
reading = ("USW00024143", "2024-01-01", 6.7)
station, date, tmax = reading
print(station, date, tmax)
low, high = 31, 12
if low > high:
    low, high = high, low
print(low, high)

Unpacking matters most in a loop. A list of tuples is a small table, with one tuple per row. for title, year, minutes in films: unpacks each row as the loop reaches it, so the body can use names instead of positions.

example-2.py · Long films, formatted
films = [("Wild Archive", 2008, 86), ("Glass Echo of Glass", 2023, 95), ("Glass Horizon on Fire", 2015, 128)]
for title, year, minutes in films:
    if minutes >= 90:
        print(f"{title} ({year}): {minutes // 60}h {minutes % 60:02d}m")
example-3.py · One name too few
reading = ("USW00024143", "2024-01-01", 6.7)
station, tmax = reading

When to use it: whenever you read a record with a fixed layout, such as a pair from enumerate, a row from a list of tuples, or two values to swap. Mistakes to avoid:

  • Getting the number of names wrong.
  • Getting the order wrong. Unpacking goes by position, so year, title = ("Wild Archive", 2008) puts the title in year with no error.
Review
  • a, b, c = record names each value of a tuple in order. The count of names must match.
  • for title, year in films: unpacks every row of a list of tuples, and a, b = b, a swaps.
  • Unpacking goes by position, so names in the wrong order give wrong values with no error.
  • Next module: dictionaries look values up by a key instead of a position.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Unpack a tuple — Lists & Tuples · Runtime