Python Iterable Unpacking
Learn how Python assigns items from an iterable to multiple targets, including starred targets, nested patterns, and clean value swapping.
Intermediate
Python assignment can do more than bind one name. When the target on the left contains multiple names, Python can unpack an iterable and assign its items to those targets. This is assignment-side unpacking; it is different from the
* and
** forms used to unpack values into a function call.
Match targets to items
With a regular target list, the iterable must provide exactly as many items as there are targets. Assignment proceeds from left to right.
|
|
The first item goes to x; the second goes to y.
The right-hand side can be any iterable, not just a tuple or list. Python obtains its items in iteration order and assigns each item to the corresponding target.
|
|
Strings are iterable, so their characters can be unpacked too.
The number of items must fit
Without a starred target, Python requires an exact match. Too few or too many items raises
ValueError. This is useful because an unexpected data shape fails immediately instead of silently dropping or inventing values.
|
|
An exact three-item iterable fits three targets.
Collect the rest with a starred target
Prefix one target with
* to collect all remaining items. There can be at most one starred target in an assignment target list, and the starred target always receives a
list. The list may be empty.
|
|
The starred target absorbs everything between the required first and last values.
|
|
A starred target can receive an empty list when no items remain.
Unpack nested structure
Targets can themselves contain another target list. Python recursively unpacks each nested iterable, so a pattern can describe structured data without manual indexing.
|
|
Each pair is unpacked again into name and score.
Unpacking can swap values
A multiple-target assignment can also swap existing bindings without a temporary variable. Python evaluates the right-hand side before assigning the targets.
|
|
The right-hand values are produced first, then assigned to the targets.
Keep assignment unpacking separate from call unpacking
In
x, y = point, the star—when present—is a target that collects items from the iterable being assigned. In
func(*point), the star is part of a function call and expands an iterable into positional arguments. The two forms use the same symbol for different language operations.
What to remember
A regular target list needs an exact number of items. A single starred target can absorb the remaining items into a list. Nested target lists mirror nested data, and multiple-target assignment can swap values cleanly. These rules belong to assignment syntax, not to the separate function-call unpacking lesson.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.