Unpacking & starred targets

Unpack a record into useful names

Lesson 13 of 20 · 10 min · Module 5: A more expressive Python toolkit

A sequence can carry several related values. Unpacking connects each position to a meaningful local name.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Use ordinary and starred unpacking
  • Give an empty remainder a useful result

The idea

Use name, *scores = record when the first item is a name and the remaining items are scores. The starred target receives a new list, including an empty list when there are no remaining items.

name, *scores = ("Alex", 80, 90)
print(name, scores)

01Read the input contract

The tuple is guaranteed to have at least a name. That matters: unpacking a completely empty tuple into name and scores would fail.

02Collect a variable-length remainder

The starred target consumes all items not assigned to the fixed targets. Here it gathers every score into a list.

first, *rest = ("Python", 1, 2)
print(first, rest)
Output
Python [1, 2]

03Use collection operations directly

len tells you how many scores exist and sum combines them. Both have sensible results for an empty list, so no special branch is needed.

Your turn

Write score_summary(record). The nonempty tuple starts with a name followed by zero or more numeric scores. Return {"name": name, "count": number_of_scores, "total": sum_of_scores}. Do not change the record.

What the checks look for

  • Summarizes several scores
  • Handles a name without scores
  • Uses a different record and keeps zero scores
Try it in the editor →

Take this with you

Unpacking turns positions into names that explain their meaning.

Go a little further

Return an average as an additional field, using zero when no scores exist.

Learn Python Foundations for free

20 short lessons with real code and instant checks.

See the whole course →