01 / 20
a b

Tuple Unpacking
& Multiple Assignment

Master the art of assigning multiple variables at once and swapping values in a single elegant line of Python.

Python

What is Multiple Assignment?

In most languages, assigning values to variables means one line per variable. Python lets you assign several variables in a single statement by separating them with commas on both sides of the equals sign.

# Traditional: one at a time x = 10 y = 20 z = 30 # Multiple assignment: all at once x, y, z = 10, 20, 30

What is a Tuple?

A tuple is an immutable sequence in Python. It looks like a list, but uses parentheses (or just commas). When you write 10, 20, 30 on the right side of an assignment, Python automatically creates a tuple.

# These are all tuples t1 = (10, 20, 30) t2 = 10, 20, 30 # parentheses are optional print(type(t2)) # <class 'tuple'>

What is Tuple Unpacking?

Tuple unpacking (also called destructuring) takes a tuple and breaks it apart, assigning each element to a separate variable. The number of variables on the left must match the number of elements on the right.

"hi" 42 3.14 , , tuple with 3 elements a = "hi" b = 42 c = 3.14 a, b, c = "hi", 42, 3.14

The Core Rule

Count Must Match
The number of variables on the left must exactly equal the number of values on the right.
Right Side First
Python evaluates all values on the right before assigning any of them. This is what makes swapping work.
# This raises ValueError! a, b = 1, 2, 3 # ValueError: too many values to unpack # This also raises ValueError! a, b, c = 1, 2 # ValueError: not enough values to unpack

How It Works Under the Hood

STEP 1 Evaluate the right side: build a tuple (5, 10) 1 STEP 2 Create a temporary tuple object in memory 2 STEP 3 Unpack: assign tuple[0] to a, tuple[1] to b 3 a = 5, b = 10 ✓ Done!

The Classic Swap

Swapping two variables is one of the most famous uses of tuple unpacking. In other languages, you need a temporary variable. In Python, one line does it all.

Other Languages
temp = a
a = b
b = temp
Python
a, b = b, a

That's it!

Assignment vs Unpacking

Simple Assignment Tuple Unpacking
Syntax x = 10 x, y = 10, 20
Variables Set One at a time Multiple simultaneously
Right Side Any single expression Tuple, list, or any iterable
Order Sequential Right side evaluated first, then assigned
Swap? Needs temp variable a, b = b, a

How to Apply It

1
Count the values you need to assign or the elements in your iterable.
2
Write the same number of variable names on the left side, separated by commas.
3
Place the iterable or comma-separated values on the right side of the equals sign.
4
Verify: left count must equal right count, or use \(\texttt{*variable}\) to capture extras.
# Example: unpacking a function return def get_point(): return 3, 7 x, y = get_point() print(x, y) # 3 7

Example 1: Basic Unpacking

# Unpack a list of RGB values colors = [255, 128, 0] red, green, blue = colors print(red) # 255 print(green) # 128 print(blue) # 0
# Unpack a string first, second, third = "abc" print(first) # a print(second) # b print(third) # c

Example 2: Swap in Action

BEFORE a 5 b 9 → a, b = b, a AFTER a 9 b 5 Values cross: right side evaluated first a, b = b, a # a=9, b=5
a = 5 b = 9 a, b = b, a print(a) # 9 print(b) # 5

Example 3: Unpacking in Loops

Tuple unpacking shines in for loops when iterating over sequences of pairs or tuples. It's especially useful with enumerate() and dict.items().

# Unpacking with enumerate() fruits = ["apple", "banana", "cherry"] for index, fruit in enumerate(fruits): print(index, fruit) # 0 apple # 1 banana # 2 cherry
# Unpacking dictionary items scores = {"Alice": 95, "Bob": 87} for name, score in scores.items(): print(name, "scored", score)

Extended Unpacking with \(*\)

What if you have more values than variables? Use the star (*) operator to capture the extras into a list.

first, *rest = [1, 2, 3, 4, 5] print(first) # 1 print(rest) # [2, 3, 4, 5] first, *middle, last = [1, 2, 3, 4, 5] print(first) # 1 print(middle) # [2, 3, 4] print(last) # 5

Using \(\_\) to Ignore Values

Sometimes you only need some values from a tuple. By convention, use _ (underscore) as a throwaway variable for values you don't need.

# Only need the filename and extension _, filename, ext = ("/home/user", "report", "pdf") print(filename) # report print(ext) # pdf # Ignore multiple values with *_ first, *_, last = range(10) print(first, last) # 0 9

Common Mistakes

✕ Mismatched Count
Writing \(\texttt{a, b = 1, 2, 3}\) raises a ValueError. Left and right sides must have the same number of elements.
✕ Sequential Thinking
Assuming \(\texttt{a, b = b, a+b}\) sets \(\texttt{a}\) to \(\texttt{b}\) first, then uses the new \(\texttt{a}\). Wrong: the old values are used on the right.
✕ Forgetting the Comma
Writing \(\texttt{a = 1, 2}\) doesn't unpack: it assigns the tuple (1, 2) to \(\texttt{a}\). You need \(\texttt{a, b = 1, 2}\).

Summary Cheat Sheet

Pattern Code Result
Basic Unpack \(\texttt{a, b = 1, 2}\) \(\texttt{a=1, b=2}\)
Swap \(\texttt{a, b = b, a}\) Values exchanged
From List \(\texttt{a, b = [1, 2]}\) \(\texttt{a=1, b=2}\)
Star Capture \(\texttt{a, *b = [1,2,3]}\) \(\texttt{a=1, b=[2,3]}\)
Ignore \(\texttt{\_, b = (1, 2)}\) \(\texttt{b=2}\)
Loop Unpack \(\texttt{for k, v in d.items()}\) Key-value pairs

Question 1 of 5

What is the output of the following code?

\(\texttt{x, y = 10, 20}\)
\(\texttt{x, y = y, x}\)
\(\texttt{print(x, y)}\)

Question 2 of 5

What happens when you run:

\(\texttt{a, b, c = [1, 2]}\)

Question 3 of 5

What is the value of \(\texttt{rest}\) after this code?

\(\texttt{first, *rest = [10, 20, 30, 40]}\)

Question 4 of 5

Given \(\texttt{a = 3}\) and \(\texttt{b = 5}\), what are the values of a and b after:

\(\texttt{a, b = b, a + b}\)

Question 5 of 5

Which of the following is NOT a valid use of tuple unpacking?