Skip to the solution
EasyDSA10 min read

How does iterable unpacking work?

1.0k views

The problem

Question presented to candidate: "Explain what happens in a line like first, *rest = items or a, b = b, a. How does iterable unpacking work in Python, what are the rules, and where else do you see the star syntax?"

What a strong answer should cover:

  • The right side is evaluated completely first, then its items are assigned to the targets on the left, from left to right; any iterable works (list, tuple, string, generator, dict keys).
  • The count must match, otherwise ValueError: too many values to unpack or not enough values to unpack.
  • One starred target (PEP 3132) collects the leftovers into a list, possibly empty; two stars are a SyntaxError.
  • Nested targets mirror nested data: name, (lat, lng) = record; it is used in for headers, enumerate, dict.items().
  • The other direction (PEP 448, Python 3.5): [*a, *b], {**d1, **d2}, f(*args, **kwargs).
  • A CPython detail: a, b = b, a compiles to a SWAP instruction on 3.11, no tuple is built; longer targets use UNPACK_SEQUENCE / UNPACK_EX.

Code / implementation expected: Yes β€” a few short assignments showing a starred target, a swap, a nested target and the error case.

  • unpacking

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonUnpacking forms: basic, starred, swap, nested, loops and spreading
PythonErrors and gotchas: count mismatch, two stars, assignment order, trailing comma

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 8 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

What is the enum module and when should you use it?

Continue