Tuple Unpacking
& Multiple Assignment
Master the art of assigning multiple variables at once and swapping values in a single elegant line of 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.
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.
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.
The Core Rule
How It Works Under the Hood
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.
a = b
b = temp
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
Example 1: Basic Unpacking
Example 2: Swap in Action
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().
Extended Unpacking with \(*\)
What if you have more values than variables? Use the star (*) operator to capture the extras into a list.
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.
Common Mistakes
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?