Skip to main content
Editor

Python Unpacking: Starred Expressions, Swapping, and Destructuring

Intermediate20 min5 exercises70 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/5 exercises

Imagine you order a package online that contains three items: a book, headphones, and a phone case. When the box arrives, you open it and put each item where it belongs. The book goes on the shelf, headphones go on the desk, and the case goes on your phone.

Python unpacking works the same way. You take a collection of values - a tuple, list, or any iterable - and assign each value to its own variable in one clean line. No need to access items one by one with indices.

In this tutorial, you'll learn basic unpacking, the elegant variable swap trick, starred expressions that capture multiple items, unpacking inside loops, and how to destructure nested data.

How Does Basic Unpacking Work?

When you have a tuple or list with multiple values, you can assign each value to a separate variable in one line. The number of variables on the left must match the number of items on the right.

Basic unpacking from tuples and lists
# Unpacking a tuple
coordinates = (10, 20, 30)
x, y, z = coordinates
print(x) # 10
print(y) # 20
print(z) # 30
# Unpacking a list
colors = ['red', 'green', 'blue']
first, second, third = colors
print(first) # red
print(second) # green
print(third) # blue
Output
10
20
30
red
green
blue

Without unpacking, you'd need to access each item by index. Unpacking makes the code shorter and much easier to read.

Without unpacking (verbose)
point = (10, 20, 30)
x = point[0]
y = point[1]
z = point[2]
print(x, y, z)
With unpacking (clean)
point = (10, 20, 30)
x, y, z = point
print(x, y, z)

You can also unpack directly in assignments without creating a named tuple first. Python creates the tuple automatically when you separate values with commas.

Unpacking without parentheses
# Direct unpacking (no parentheses needed)
name, age, city = 'Alice', 25, 'Paris'
print(name) # Alice
print(age) # 25
print(city) # Paris
# This works because Python sees commas and creates a tuple
print(type(('Alice', 25, 'Paris'))) # <class 'tuple'>
Output
Alice
25
Paris
<class 'tuple'>

How to Swap Variables in One Line

In most programming languages, swapping two variables requires a temporary variable. Python's unpacking makes this unnecessary. You can swap values in a single, elegant line.

Swapping two variables
a = 'hello'
b = 'world'
# Swap in one line!
a, b = b, a
print(a) # world
print(b) # hello
Output
world
hello

This works because Python evaluates the right side first, packing the values into a tuple (b, a), and then unpacks them into a, b. The whole thing happens safely in one step.

Other languages (need temp variable)
a = 1
b = 2
temp = a
a = b
b = temp
print(a, b)  # 2 1
Python (one line)
a = 1
b = 2
a, b = b, a
print(a, b)  # 2 1

You can swap three or more variables the same way. Python handles it all in one step.

Rotating three variables
# Rotate three variables
a, b, c = 1, 2, 3
print(f'Before: a={a}, b={b}, c={c}')
a, b, c = b, c, a
print(f'After: a={a}, b={b}, c={c}')
Output
Before: a=1, b=2, c=3
After:  a=2, b=3, c=1

What Are Starred Expressions (*rest)?

Sometimes you don't know exactly how many items a collection has, or you only care about a few specific items. The starred expression (*variable) captures any leftover items into a list.

Starred expressions capture leftover items
# Capture the first item and everything else
numbers = [1, 2, 3, 4, 5]
first, *rest = numbers
print(first) # 1
print(rest) # [2, 3, 4, 5]
# Capture the last item and everything before it
*beginning, last = numbers
print(beginning) # [1, 2, 3, 4]
print(last) # 5
Output
1
[2, 3, 4, 5]
[1, 2, 3, 4]
5

You can place the star in the middle too. This is great when you know the first and last items but want to skip everything between them.

Star in the middle
scores = [95, 80, 75, 90, 85, 70, 88]
# Get the first, last, and everything in between
first, *middle, last = scores
print(f'First: {first}') # 95
print(f'Middle: {middle}') # [80, 75, 90, 85, 70]
print(f'Last: {last}') # 88
Output
First: 95
Middle: [80, 75, 90, 85, 70]
Last: 88
Star with zero items and strings
# Star captures zero items (still a list)
a, b, *rest = [10, 20]
print(a) # 10
print(b) # 20
print(rest) # []
# Star from a string
first, *middle, last = 'Hello'
print(first) # H
print(middle) # ['e', 'l', 'l']
print(last) # o
Output
10
20
[]
H
['e', 'l', 'l']
o

How to Use Unpacking in For Loops

Unpacking shines inside for loops. When you loop over a list of tuples (or lists), you can unpack each item directly into named variables instead of accessing them by index.

Unpacking tuples in a for loop
# List of (name, age) tuples
students = [
('Alice', 16),
('Bob', 15),
('Charlie', 17),
]
# Unpack each tuple in the loop
for name, age in students:
print(f'{name} is {age} years old')
Output
Alice is 16 years old
Bob is 15 years old
Charlie is 17 years old

This pattern is used constantly with enumerate() and dict.items(). Both return tuples, and unpacking makes the code much cleaner.

Unpacking with enumerate() and dict.items()
# enumerate() returns (index, value) tuples
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
print(f'{i}: {fruit}')
print()
# dict.items() returns (key, value) tuples
ages = {'Alice': 16, 'Bob': 15, 'Charlie': 17}
for name, age in ages.items():
print(f'{name} -> {age}')
Output
0: apple
1: banana
2: cherry

Alice -> 16
Bob -> 15
Charlie -> 17

How to Unpack Nested Data Structures

Python unpacking can go multiple levels deep. If a value inside your collection is itself a tuple or list, you can unpack it by using nested parentheses on the left side.

Nested unpacking with parentheses
# A tuple containing a nested tuple
record = ('Alice', (95, 87, 92))
# Nested unpacking
name, (score1, score2, score3) = record
print(f'{name}: {score1}, {score2}, {score3}')
Output
Alice: 95, 87, 92

This works at any depth. You can even combine nested unpacking with a starred expression: name, (first, *others) = ('Alice', (95, 87, 92)) puts 95 in first and [87, 92] in others.

Nested unpacking in loops
# List of students with (name, (math, science, english))
students = [
('Alice', (95, 87, 92)),
('Bob', (78, 85, 90)),
('Charlie', (88, 92, 76)),
]
for name, (math, science, english) in students:
avg = (math + science + english) / 3
print(f'{name}: average = {avg:.1f}')
Output
Alice: average = 91.3
Bob: average = 84.3
Charlie: average = 85.3

Common Unpacking Mistakes to Avoid

Unpacking is intuitive once you get the hang of it, but there are a few pitfalls that catch beginners.

Common unpacking mistakes
# Mistake 1: Forgetting parentheses in nested unpacking
# Wrong: name, x, y = ('Alice', (10, 20)) -> ValueError!
# Right:
name, (x, y) = ('Alice', (10, 20))
print(name, x, y)
# Mistake 2: Unpacking a single-item tuple
# You need the comma to make it a tuple!
value, = (42,) # Note the comma after 42
print(value) # 42
# Mistake 3: Forgetting that * always creates a list
first, *rest = 'AB'
print(type(rest)) # <class 'list'>, not str!
Output
Alice 10 20
42
<class 'list'>

Practice Exercises

Unpack a Coordinate
Write Code

Unpack the tuple point into three variables: x, y, and z. Then print them on one line separated by spaces using print(x, y, z).

point = (7, 14, 21)
# Unpack into x, y, z and print them
Swap Two Variables
Write Code

The variables first and second have the wrong values. Swap them using Python's unpacking syntax (one line, no temporary variable), then print both.

first = 'goodbye'
second = 'hello'
# Swap first and second in one line
print(first)
print(second)
Head and Tail with Star
Write Code

Use a starred expression to unpack the numbers list into head (the first item) and tail (everything else). Print both on separate lines.

numbers = [10, 20, 30, 40, 50]
# Unpack into head and tail using *
Predict the Unpacking Output
Predict Output

What does this code print? Think about what the star captures and what type it becomes.

a, *b, c = [1, 2, 3, 4, 5, 6]
print(a)
print(b)
print(c)

Write three print() statements that produce the exact same output.

# Predict the output and write the matching print statements
print("?")
print("?")
print("?")
Unpack Student Records
Write Code

You have a list of student records. Each record is a tuple of (name, (math_score, english_score)). Use nested unpacking in a for loop to calculate and print each student's average score.

Print each line in the format: Name: average where average is rounded to 1 decimal place using :.1f.

students = [
('Alice', (90, 80)),
('Bob', (70, 90)),
('Charlie', (85, 95)),
]
# Loop with nested unpacking and print averages

Harder problems

More problems on this topic: Python idioms

Related Tutorials

Was this tutorial helpful?