Lesson · Core Collections
Unpacking & Starred Expressions
69 min readUnpacking & Starred Expressions
Unpacking assigns elements from an iterable to multiple targets. Starred expressions extend that idea to variable-length data and to combining containers and function arguments.
Learning goals
- Unpack a sequence into fixed targets and one starred target, and state what the starred name receives (a list, even when empty).
- Explain why
first, *middle, last = valuesputs the star in the middle and how the position decides what it collects. - Use
*in displays and calls and**in displays and calls, and name what each expansions feeds. - Perform a swap with
a, b = b, aand explain why Python evaluates the right side before rebinding targets. - Predict the failures for too many or too few targets, two competed stars, and a keyword duplicated through
**.
Mental model
Because the right side is evaluated before any target is bound, patterns like a, b = b, a and starred splits need no temporary. The star is greedy over the middle: it absorbs whatever the fixed targets on both sides leave behind, which is why only one starred target is allowed per assignment level.
Unpacking is assignment by pattern
fixed targets claim the ends; one star absorbs the middle
Mental model
the same mechanism as a compact list
evaluate the right-hand iterable fully
↓ bind targets left to right
fixed target → one element; nested target → recurse into its structure
starred target → collects the leftover middle into a list (possibly empty)
↓ beyond assignment, the same stars splat into displays and calls
[*a, *b] rebuilds a sequence; f(*args) spreads positional arguments
{**a, **b} merges mappings; f(**kw) spreads keyword argumentsCore idea
Unpacking is pattern-directed assignment over iteration: the right side is evaluated first, then the target pattern fills left to right, with a single starred target absorbing the middle into a list. The same star generalizes beyond assignment, splatting iterables into calls and displays with * and mappings into keyword arguments and dict literals with **. A target pattern describes a shape, so the common failures are shape failures: too many values, too few, or two stars competing for one middle.
Tuple and iterable unpacking
Unpacking is based on iteration, not on tuples specifically. Any iterable that yields the required number of values can supply targets such as a, b = iterable.
Nested unpacking
Targets can mirror nested iterable structure, such as name, (x, y) = record. The runtime requires the supplied structure to match the target pattern.
Swapping values
Unpacking makes swapping concise because Python evaluates the right side before rebinding the left-side targets. No temporary name is required in user code.
Extended unpacking with *
One starred target can collect zero or more remaining items into a list. It is useful for head/tail or first/middle/last decompositions.
Ignoring values by convention with _
Using _ as an unpacking target conventionally says that a value is intentionally unused. It is still an ordinary name and can be rebound.
Unpacking in loops
A for target can unpack each iterated item directly, such as for key, value in mapping.items(). This keeps element structure visible at the loop boundary.
*iterable in calls
*iterable expands items into positional arguments at a call site. The resulting positional arguments must still satisfy the target function signature.
**mapping in calls
**mapping expands string-keyed entries into keyword arguments. Duplicate bindings, including a name already supplied explicitly, raise TypeError.
List/set/dict display unpacking
Starred unpacking can build new collection literals from existing iterables or mappings. The result is a new outer collection; referenced elements are not automatically copied.
Merge patterns and readability boundaries
Unpacking is excellent for small explicit merges, but a long chain of starred inputs can hide precedence and allocation cost. Use named intermediate steps when merge policy matters.
Walkthrough
values = [10, 20, 30, 40, 50]is any iterable, andfirst, *middle, last = valuesbindsfirstto 10 andlastto 50 because the fixed targets claim the ends, leavingmiddleto collect the leftover middle as the list[20, 30, 40].combined = [*left, *right]builds a new list rather than merging in place: neitherleftnorrightchanges, and the new object holds their items in order,[1, 2, 3, 4].config = {**defaults, "timeout": 10}merges the mapping and then applies the explicit key, so"timeout"ends as 10 while"retries"keeps its default of 2; the explicit entry wins because it comes after the splat.- Predict before running: the three values printed for
first, middle, last, plus the finalcombinedlist andconfigdict. Check the type ofmiddleas well, since a starred target always collects into a list.
Experiments to try
- Move the star and run both
*head, last = valuesandfirst, *rest = values; write down what each name collects before checking, and compare both with the original middle-star split. - Try the empty middle case:
first, *middle, last = [1, 2]. Confirm the assignment succeeds and record exactly whatmiddlecontains. - Swap two names with
a, b = 1, 2followed bya, b = b, a; print both after the swap, then repeat the swap using a temporary variable and say which version communicates the intent. - Splat into a call: define
def area(width, height): return width * heightand callarea(*[3, 4])andarea(**{"width": 3, "height": 4}); then trigger the duplicate error witharea(3, **{"width": 4, "height": 4})and read the message.
Playable lesson
Lab: Unpacking visualizer
Animate values flowing from an iterable into normal and starred targets. Include too-many, too-few, and multiple-star error cases.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Unpacking visualizer
values = [10, 20, 30, 40, 50]
Source iterable
10 [20, 30, 40] 50
Predict first
What does `middle` receive?
The fixed targets claim the two ends, and the one starred target absorbs everything left in the middle into a list.
Common mistakes
- Starving the fixed targets: too few values for the unstarred names raises
ValueError, and two starred targets likea, *b, *c = valuesare aSyntaxErrorbecause the middle can only be absorbed once. - Forgetting that a starred target always collects into a list:
first, *rest = "abc"givesrest = ['b', 'c'], not a string, and an empty remainder gives[]rather thanNone. - Assuming a splat merge mutates its sources:
[*left, *right]and{**defaults, **overrides}create new objects, so the original lists and dicts keep their contents. - Duplicating a keyword through
**: callingarea(3, **{"width": 4})raisesTypeErrorbecause the positional3already bound thewidthparameter, and the same name arrives again from the mapping.
Practice: Easy
- Unpack
first, *middle, last = [10, 20, 30, 40, 50]and print all three names. Predict the type and contents ofmiddlebefore running, then confirm withtype(middle). - Run the split twice more, once as
*head, last = valuesand once asfirst, *rest = values. Write down what each name collects first, then check against the output. - Assign
a = 1,b = 2, swap them with a singlea, b = b, a, and print both. Repeat the swap with a temporary variable and say which version makes the intent clearer.
Practice: Medium
- Create
left = [1, 2]andright = [3, 4], then buildcombined = [*left, *right]; check thatleftandrightare unchanged afterward, which shows the display built a new list. - Merge
defaults = {"timeout": 5, "retries": 2}withoverrides = {"timeout": 10}in both orders,{**defaults, **overrides}and{**overrides, **defaults}. State which value wins for"timeout"in each and connect the rule to dict literal order. - Define
def total(a, b, c): return a + b + cand call it twice, once astotal(*[1, 2, 3])and once astotal(**{"a": 1, "b": 2, "c": 3}). Explain what each splat matched to in the signature.
Practice: Hard
- Design
head_tail(records)that returns(first, rest)for any non-empty iterable and document the behavior for an empty one (decide, for example, that the unpack raisesValueError). Test it with a list, a string, and an empty list. - Build a failure lab with three entries: too few values for the fixed targets, two starred targets in one assignment (caught as a
SyntaxErrorbefore running), and a call where**duplicates an already supplied parameter. Record the exact error type for each and explain the mechanism. - Compare the example's one-line merges with named intermediate steps for a three-source merge, for example
{**a, **b, **c}versus building a copy and updating it twice. Say which form makes precedence obvious when keys collide and which one you would review faster.
Lesson checklist
- I can split any iterable into fixed targets plus one starred target and say what the star collects.
- I can explain why the right side is evaluated before the targets are bound, using the swap as evidence.
- I can use
*and**in displays and calls and name what each splat feeds. - I can predict the failures: too few values, two competing stars, and a duplicated keyword through
**.
Remember
Unpacking is assignment by pattern: the right side is evaluated first, then the fixed targets fill from the ends while one starred target absorbs the middle into a list. The same star travels beyond assignment, splatting iterables into calls and displays with `*` and mappings into keyword arguments and dict literals with `**`. Because patterns describe shapes, failures are shape failures: too few values, two stars competing, or a keyword that arrives twice.
Interview angles
What is the main purpose of **Tuple and iterable unpacking**?+
Unpacking is based on iteration, not on tuples specifically. Any iterable that yields the required number of values can supply targets such as a, b = iterable.
What should you pay attention to when using **Nested unpacking**?+
Targets can mirror nested iterable structure, such as name, (x, y) = record. The runtime requires the supplied structure to match the target pattern.
How does **Swapping values** fit into this lesson?+
Unpacking makes swapping concise because Python evaluates the right side before rebinding the left-side targets. No temporary name is required in user code.
What does `first, *rest = "abc"` bind to `rest`?+
rest receives ['b', 'c'] as a list: a starred target always collects into a list, regardless of the source type. When nothing remains, it is bound to an empty list rather than to None.