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 unpackornot 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 inforheaders,enumerate,dict.items(). - The other direction (PEP 448, Python 3.5):
[*a, *b],{**d1, **d2},f(*args, **kwargs). - A CPython detail:
a, b = b, acompiles to aSWAPinstruction on 3.11, no tuple is built; longer targets useUNPACK_SEQUENCE/UNPACK_EX.
Code / implementation expected: Yes β a few short assignments showing a starred target, a swap, a nested target and the error case.