ReviseAlgo Logo

Tuples

Tuple Unpacking

Multiple assignment with tuples

Interview: Core Pythonic idiom — interviewers expect fluent unpacking usage

Last Updated: June 12, 2026 8 min read

Tuple unpacking (also called destructuring) assigns elements of a tuple/iterable to multiple variables in a single statement. It's one of Python's most elegant features and is used pervasively in real-world code.

Basic Unpacking

  • Simple: x, y, z = (1, 2, 3)
  • Swap: a, b = b, a — no temp variable needed!
  • From functions: lo, hi = min_max(data)
  • Must match: Number of variables must match number of elements (or use *)

Extended Unpacking (Python 3)

  • Star operator: first, *rest = [1, 2, 3, 4] — first=1, rest=[2,3,4]
  • Middle star: first, *middle, last = [1, 2, 3, 4] — middle captures remaining
  • Star collects as list: The starred variable always gets a list, even if empty
  • Only one star: Can't have multiple starred variables in one unpacking

Advanced Patterns

  • Ignore values: Use _ as throwaway: x, _, z = (1, 2, 3)
  • Nested unpacking: (a, b), (c, d) = [(1, 2), (3, 4)]
  • In for loops: for key, value in dict.items():
  • Function args: func(*args) unpacks tuple as positional arguments

Interview Tip

The swap idiom a, b = b, a is frequently asked in interviews. Under the hood, Python creates a temporary tuple on the right side (packing) and unpacks it to the left side.

Use Cases

Swapping variables without temporary storage

Extracting function return values (multiple returns)

Parallel iteration with zip and enumerate

Head/tail decomposition in recursive algorithms

Common Mistakes

Mismatching variable count and element count (raises ValueError)

Forgetting that the starred variable always gets a list (not a tuple)

Using multiple starred variables in one unpacking (SyntaxError)

Not knowing _ is just a convention — it's a valid variable name that can be reassigned