Python Extended Unpacking with a Star
Core idea
Use a starred target such as *rest when the number of items may vary. Unstarred targets still require one item each; the starred target collects everything left into a list, even when the source is a tuple. Only one starred target is allowed at a single unpacking level.
header, *values = ("stock", 4, 8, 2)print(header)print(values)The first item is assigned separately; the rest form a list.
Keep the endpoints
first, *middle, last = (3, 5, 7, 9)print(first, middle, last)The middle target collects values between the two endpoints.
An empty remainder
The starred target is still a list when no items remain.
Common mistake
first, *rest = () raises ValueError because first needs an item. A starred target is not a way to make every target optional.
Practice
Use first, *middle, last with (2, 8) and predict middle before running it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Extended unpacking
Check your understanding of extended unpacking.
What is printed?
a, *rest = (2, 4, 6)print(rest)What is printed?
a, *middle, b = (3, 5)print(middle)Which error occurs?
a, *rest = ()How many starred targets are permitted at a single unpacking level?