liveBook · Manning

Starred target

As explained in Python How-To

A starred expression is Python unpacking syntax prefixed with an asterisk that captures all otherwise unmatched items into a list.

When sequence unpacking must preserve the first and last items while collecting everything between them, use a starred target such as `lowest, *middle, highest = scores`. The asterisk marks a variable that captures all otherwise unmatched items in a list. This avoids indexing each position separately and handles sequences with different numbers of middle items. section 4.4.2

lowest2, *middles2, highest2 = player_scores    #1
final2 = sum(middles2) / len(middles2)
 
assert lowest0 == lowest2 == player_scores[0]
assert middles0 == middles2 == player_scores[1:-1]
assert highest0 == highest2 == player_scores[-1]

The unpacking form produces the same lowest, middle, and highest values as explicit indexing while keeping the middle values in a list for later calculation. section 4.4.2

Keep these rules in mind when using a starred target:

  • Place the asterisk before the target name, as in `*middle`. section 4.4.2
  • Capture all items not assigned to the other targets; the captured value is always a list, even when the source is a string. section 4.4.2
  • Allow the starred target to capture zero items, which produces an empty list. section 4.4.2
  • Use only one starred target in an assignment; two starred targets cause a syntax error because the remaining items cannot be assigned unambiguously. section 4.4.2

Capture a variable-length middle

For `first_score, *scores, last_score = [9.1, 8.9]`, `scores` becomes `[]`. With a longer sequence, it contains every item between the first and last values, ready for operations such as `sum(scores) / len(scores)`. section 4.4.2

How Python How-To covers it

How deep it goes
Defines capture behavior, result type, empty captures, and the single-star restriction without descending into interpreter internals.
Examples
Uses player scores, a string, an empty middle capture, and an invalid assignment with two starred targets.
What it assumes
Assumes familiarity with sequences and ordinary one-to-one unpacking while reinforcing alternative unpacking methods.
What you can do after
Apply it via Python unpacking to extract fixed positions and retain variable-length remainder data as a list.
How it connects
Connects starred expressions to tuple unpacking, sequence data, iterables, indexing, and list results.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.