Why does unpacking two values fail when my list has three items?
Quick answer
Without a starred target, Python requires the iterable to contain exactly as many items as there are assignment targets. So assigning a three-item list to two names fails. Add * to one target to collect the remaining items into a list: first, second, *rest = [10, 20, 30] gives rest the value [30]. If no items remain, rest is an empty list. [S1]
The question, the details, the next step.
A practical checklist
Count the assignment targets on the left side.
Check how many items the right-side iterable contains.
Use ordinary unpacking when the counts should match exactly.
Add one starred target when remaining items should be collected into a list.
Confirm there are enough items to fill every non-starred target.
A few more useful answers
Does the starred target receive a tuple?
No. In assignment unpacking, the items gathered by the starred target are collected into a list. [S1]
Can the starred target be empty?
Yes. If the other targets are filled and no items remain, the starred target receives an empty list. [S1]
Does adding `*rest` make any input length valid?
No. The iterable must still have enough items to fill the targets outside the star; the star collects the remaining items. [S1]
Sources
References used for this guide.
- [S1] Python Language Reference: Assignment statements and unpacking docs.python.org · Checked
