Topic 48 of 64
Tuple Unpacking
Overview
Tuple unpacking (destructuring) lets you assign multiple variables from a sequence in one line. It works with any iterable and enables clean swap syntax, function multi-returns, and starred expressions.
Syntax
python
# Basic unpacking
x, y = (3, 4)
a, b, c = [1, 2, 3]
first, second = "hi" # works on strings too!
# Swap without temp variable
a, b = b, a
# Starred unpacking (extended)
first, *rest = [1, 2, 3, 4, 5]
# first = 1, rest = [2, 3, 4, 5]
*init, last = [1, 2, 3, 4, 5]
# init = [1, 2, 3, 4], last = 5Common Pitfalls
- The number of variables must match the iterable length unless using * — mismatch raises ValueError.
- Only one starred expression is allowed per unpacking statement.
- Interview tip: Swapping with tuple unpacking (a, b = b, a) is more Pythonic than using a temp variable and is a common interview test.
Real-World Example
Unpack CSV row data into named variables for clean processing
example
python
import csv
from pathlib import Path
def process_csv(path: str) -> None:
with open(path) as f:
reader = csv.reader(f)
next(reader) # skip header
for name, age, email, *extras in reader:
age = int(age)
print(f"{name} ({age}): {email}")
# Swap example — classic interview trick
a, b = 1, 2
a, b = b, a
print(a, b) # 2 1