Sub topic 8
Capturing the rest with starred targets
This chapter assumes you know basic unpacking (a, b = pair), list indexing and slicing, and how to write a for loop. Here you will learn how a starred target collects the leftover items of an unpacking.
The problem with fixed-length unpacking
Plain unpacking needs the number of names to match the number of items. That is awkward when you only care about the first or last few items and the length varies.
a, b = (1, 2, 3)This line raises ValueError: too many values to unpack (expected 2). A starred target fixes this by absorbing the extra items.
The starred target
Put * in front of one name on the left side. Python assigns the other names first, then gives the starred name everything left over.
first, *rest = [1, 2, 3, 4]
print(first, rest)
head, *middle, last = range(5)
print(head, middle, last)The output is:
1 [2, 3, 4]
0 [1, 2, 3] 4Three facts to remember:
- The starred name is always a list, even when you unpack a tuple, a string or a
range. - The starred name can be empty. Its value is then
[]. - Only one starred target is allowed in a single unpacking.
first, *rest = (10,)
print(first, rest)
a, *b, c = "xy"
print(a, b, c)This prints 10 [] and then x [] y. The starred list is empty in both cases, and the statement still succeeds.
How Python assigns the pieces
Python reads the value once and counts how many items it has. It gives each plain name one item from the front or the back, and the starred name gets whatever is in between.
The diagram below shows this for head, *middle, last = range(5).
Where the star can go
The starred target can be first, last or in the middle. Each position suits a different task.
| Pattern | What it does | Example result for `[1, 2, 3, 4]` |
|---|---|---|
| `first, *rest = data` | Splits off the first item | `1`, `[2, 3, 4]` |
| `*init, last = data` | Splits off the last item | `[1, 2, 3]`, `4` |
| `first, *mid, last = data` | Keeps both ends | `1`, `[2, 3]`, `4` |
| `*_, last = data` | Keeps only the last item | `4` |
By convention, _ names a value you intend to ignore. *_ discards the leftovers without giving them a meaningful name.
A practical example
Suppose each line of a file holds a name followed by any number of scores. Starred unpacking separates the two parts cleanly.
rows = [
("Ada", 95, 88, 91),
("Linus", 70),
("Grace", 100, 99),
]
for name, *scores in rows:
average = sum(scores) / len(scores)
print(f"{name}: {average:.1f}")The starred name works in a for target too. Each row can have a different length, and scores is a list every time. Every row here has at least one score. A row with only a name would give an empty scores and make len(scores) zero, which would raise ZeroDivisionError.
Common errors
- Too few items. The starred name can be empty, but the plain names still need items.
a, b, *c = [1]raisesValueError: not enough values to unpack (expected at least 2, got 1). - Two stars.
*a, *b = datais aSyntaxError, because Python cannot decide where one list ends and the next begins. - A lone star.
*a = datais aSyntaxError. Writea = list(data)or(*a,) = datainstead. - Expecting a tuple. If later code needs a tuple, convert with
tuple(rest).
Exercise
What do a, b and c hold after a, *b, c = (7, 8), and what type is b?
Show answer
a is 7, c is 8, and b is an empty list []. The plain names take one item each from the two ends, so nothing remains for the starred name. b is a list, not a tuple.
Exercise
Write one line that stores the first item of values = [5, 6, 7, 8] in top and the remaining items in others.
Show answer
top, *others = values gives top == 5 and others == [6, 7, 8].