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
