3. Unpacking

Unpacking assigns the elements of a tuple to several variables in one statement:

The number of names on the left must match the number of elements. Otherwise Python raises ValueError:

The parentheses around the tuple are optional, and the same syntax swaps two variables:

A starred target collects the remaining elements into a list, even when you unpack a tuple:

rest is [2, 3, 4], not (2, 3, 4): the * always builds a new list from the leftover values.

If you only need some of the values, use _ for the ones you want to ignore:

_ is not special syntax: it is a normal variable name that programmers use by convention to say "I am not going to use this value". You could write age instead, but _ makes the intention clear.

Coming from JavaScript? This is array destructuring: x, y = point is const [x, y] = point. A starred target collects the rest into a list, even when unpacking a tuple.

#01

Unpack two values

Create point = (3, 5), then unpack it into the variables x and y with one assignment. Print x, then print y.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Unpack three values

Create rgb = (255, 128, 0) and unpack it into red, green and blue with one assignment. Print the three variables with a single print().

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Swap two values

Python can swap two variables in one assignment because the right side is a tuple. Start with a = 1 and b = 2, swap them with a, b = b, a, then print a and b.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Collect the rest

A starred target collects the remaining elements into a list. Create numbers = (1, 2, 3, 4), unpack it into first and rest with first, *rest = numbers, then print first and rest.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

Unpack the wrong number of values

The number of names must match the number of elements. Create pair = (1, 2, 3) and try to unpack it into a and b. Running the code must stop with:

Create a free account to save your progress and unlock chapter 2.