Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Core language & syntaxJuniorCommonPractical

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

Python example
first, *middle, last = [1, 2, 3, 4, 5]

sets

Python example
first = 1

,

Python example
last = 5

and

Python example
middle = [2, 3, 4]

.

#unpacking#syntax

Sources

The Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basicsThe Python Language ReferencePython Software Foundation · Precise scoping, evaluation order and expression semantics