How does Python swap two variables without a temporary variable, and how does extended unpacking with `*` work?
Answer
`a, b = b, a` works because Python's assignment statement evaluates the entire right-hand side expression list first — producing an ordered sequence of the old `b` and `a` values — and only then assigns those values to the left-hand targets in order, so no separate temporary variable is needed in user code. (Whether CPython actually allocates a tuple object for this or optimizes it into a direct stack swap is an implementation detail; the language only guarantees the evaluate-then-assign order, not a specific allocation.) Extended unpacking lets a starred name absorb any number of remaining elements: `first, *middle, last = values` binds `first` and `last` to the ends and collects everything else into a list `middle`.
Strong answer includes
- right-hand side is fully evaluated before any assignment happens
- no explicit temp variable needed in user code
- starred name collects remaining elements into a list
Practical example
first, *middle, last = [1, 2, 3, 4, 5]sets
first = 1,
last = 5and
middle = [2, 3, 4].