Sub topic 8
Capturing the rest with starred targets
This chapter assumes you can already do fixed-length unpacking such as x, y = point, and that you know how lists, slices and for loops work. It builds on those to handle sequences whose length you don't know in advance.
The problem starred targets solve
Plain unpacking needs the number of names to equal the number of items. That is awkward when you only care about the ends of a sequence, or when the length varies from call to call.
You could slice instead:
numbers = [10, 20, 30, 40, 50]
first = numbers[0]
rest = numbers[1:]
print(first, rest)A starred target does the same job in one statement and also says what shape you expect. Put * in front of one name, and that name receives every item the other names didn't take.
numbers = [10, 20, 30, 40, 50]
first, *rest = numbers
print(first, rest)
*init, last = numbers
print(init, last)
head, *middle, tail = numbers
print(head, middle, tail)This prints:
10 [20, 30, 40, 50]
[10, 20, 30, 40] 50
10 [20, 30, 40] 50How Python assigns the items
The plain names claim items first, from the left and from the right. Whatever remains in the middle goes to the starred name. The diagram shows this for head, *middle, tail = numbers.
The starred name has three properties you should remember:
- It is always a
list, even when the source is a tuple, a string or a generator. - It can be empty. It is
[]when the plain names use up every item. - It can sit at the start, in the middle, or at the end of the target list.
t = (1, 2, 3)
x, *rest = t
print(rest, type(rest))
a, *b, c = (1, 2)
print(a, b, c)This prints:
[2, 3] <class 'list'>
1 [] 2Because the result is a list, you get a mutable copy of the leftovers. A tuple on the right-hand side stays unchanged.
What counts as a source
The right-hand side can be any iterable, not only a sequence. Python consumes it completely to fill the starred name.
def countdown(n):
while n > 0:
yield n
n -= 1
top, *others = countdown(4)
print(top, others)
first, *letters = "hello"
print(first, letters)This prints:
4 [3, 2, 1]
h ['e', 'l', 'l', 'o']The generator is exhausted after the assignment. If you need the values again, build a new generator.
from itertools import count
nums = count(1)
a, b = next(nums), next(nums)
print(a, b, next(nums))This prints 1 2 3. Each next() call takes one value and leaves the rest untouched.
Patterns in the table
For data = [1, 2, 3, 4], these targets give the results below.
| Target | Names bound | Notes |
|---|---|---|
| `a, *b = data` | `a=1`, `b=[2, 3, 4]` | Head and tail |
| `*a, b = data` | `a=[1, 2, 3]`, `b=4` | Everything but the last |
| `a, *b, c = data` | `a=1`, `b=[2, 3]`, `c=4` | Both ends |
| `a, b, *c = data` | `a=1`, `b=2`, `c=[3, 4]` | Several leading names |
| `a, b, c, d, *e = data` | `e=[]` | Star is empty, not an error |
| `*a, = data` | `a=[1, 2, 3, 4]` | The trailing comma is required |
The last row is unusual. A lone *a = data is a SyntaxError with the message "starred assignment target must be in a list or tuple". The trailing comma turns the target into a one-element tuple, which is allowed. It is rarely useful, because list(data) says the same thing more clearly.
Discarding the middle or the end
When you want the ends and don't care about the middle, the convention is to name the starred target _.
first, *_, last = range(10)
print(first, last)This prints 0 9. The name _ still holds a list of the discarded items, so you pay the cost of building it. For large inputs, indexing with data[0] and data[-1] is cheaper and works on sequences without consuming anything.
Practical uses
Splitting a command from its arguments
line = "copy a.txt b.txt --force"
command, *arguments = line.split()
print(command, arguments)This prints copy ['a.txt', 'b.txt', '--force']. If the line contains only copy, arguments is an empty list and the code still works. If the line is empty, split() returns [] and the statement raises ValueError, because the plain name command has nothing to bind.
Separating a header row from the data
Starred targets also work in for loop targets, so you can peel off a header first and then split each record.
rows = [
("name", "q1", "q2", "q3"),
("Ada", 90, 85, 92),
("Linus", 70, 80, 75),
]
header, *records = rows
for name, *scores in records:
print(name, scores, sum(scores) / len(scores))This prints:
Ada [90, 85, 92] 89.0
Linus [70, 80, 75] 75.0Each record can have any number of scores, and the loop still works. Note that records is a list of the remaining tuples, and scores is a fresh list in each iteration.
Nested patterns
A starred target can appear at any level of a nested pattern. Each level of parentheses or brackets is unpacked on its own, and each level may have one star.
record = ("Oslo", (59.91, 10.75, 23, "NO"))
city, (lat, lon, *extra) = record
print(city, lat, lon, extra)This prints Oslo 59.91 10.75 [23, 'NO']. The outer pattern has no star and needs exactly two items. The inner pattern has a star, so it needs at least two items.
Errors you will meet
Three mistakes account for most failures with starred targets.
- Too few items for the plain names.
- More than one star in a single target.
- A star with no surrounding tuple or list syntax.
The first is a runtime ValueError. The message says "at least" because the star can absorb extra items but cannot invent missing ones.
try:
a, *b, c = [1]
except ValueError as e:
print(e)This prints not enough values to unpack (expected at least 2, got 1).
The second is a compile-time SyntaxError. With two stars Python could not decide how to split the middle items between them, so it rejects the statement before running anything. Using exec lets us catch it here.
try:
exec("a, *b, *c = [1, 2, 3]")
except SyntaxError as e:
print(e)This prints multiple starred expressions in assignment. The third error, a bare *a = data, was covered in the table above.
The same symbol on the other side
The * also appears on the right-hand side of an expression, where it does the opposite job. It spreads an iterable into a new tuple, list or set instead of collecting items into a list.
left = (1, 2)
right = [3, 4]
combined = (*left, *right)
print(combined)
print([0, *left, 99])This prints:
(1, 2, 3, 4)
[0, 1, 2, 99]Here you may use as many stars as you like, because nothing needs to be divided. On the left of = the star collects, and on the right it expands. Spreading arguments in a function call uses the same expansion rule and is covered in a later chapter.
Cost and when to prefer slicing
Starred targets always build a new list. That is fine for short inputs and a poor fit for repeated processing of long ones. A classic trap is recursion that peels one item at a time.
def total(items):
if not items:
return 0
head, *tail = items
return head + total(tail)
print(total([1, 2, 3, 4]))This prints 10, but every call copies the remaining items. The work grows with the square of the length, and Python's default recursion limit (about 1000 frames) stops the function on long inputs. A plain sum(items) or a loop is the right tool here.
Use these rules of thumb to decide between a star and a slice:
- Use a star when the shape of the data is the point, such as "a command followed by arguments", and the input is small.
- Use slicing or indexing when you only need one end, or when the sequence is large.
- Use
next()orislicewhen the source is an iterator that could be long or endless.
Summary of the rules
- A target list may contain at most one starred name.
- The starred name receives a list of the leftover items, which may be empty.
- Every plain name must still get an item, so the source needs at least as many items as there are plain names.
- The source can be any finite iterable, and it is consumed completely.
- Stars work in assignments,
fortargets and nested patterns.
Exercise
What are the values of a, b and c after a, *b, c = "xy", and what type is b?
Show answer
a is 'x', c is 'y', and b is the empty list []. The star is a list even though the source is a string, and it is empty because the two plain names use both characters.
Exercise
Write code that takes values = [4, 8, 15, 16, 23, 42] and binds smallest_first to the first item, last to the last item, and middle_total to the sum of the items between them. Then say what happens if values has only one item.
Show answer
Use smallest_first, *middle, last = values followed by middle_total = sum(middle), which gives 4, 42 and 54. With a one-item list the statement raises ValueError: not enough values to unpack (expected at least 2, got 1), because the two plain names need two items.