Unpacking Values
Unpacking assigns each value in a list to a separate variable in one line.
The idea
Put the variable names on the left of =, separated by commas:
first, second, third = [3, 5, 2]print(first, second, third)This prints 3 5 2. Names receive values in order: first gets 3,
second gets 5, and third gets 2.
Unpack a stored list
You can unpack a list already stored in a variable. Choose names that describe the values:
reading = ["Hobart", 12]city, temperature = readingprint(city)print(temperature)This prints Hobart, then 12. The first name receives the first item,
even when the items have different types.
The counts must match
Two names need exactly two values:
first, second = [10, 20]print(first)print(second)This prints 10, then 20. Unpacking also works with tuples and other
iterables, with the same rule: the number of values must match the number of
names.
Note: Too few or too many values raises ValueError.
Try changing the list to [10] or [10, 20, 30] and running it again.
See also: Lists, Variables, Nested Data.
Your turn
Add two lines: unpack rolls into first, second, and third, then print
second.
6
rolls = [4, 6, 1]# add two lines: unpack, then print the middle valueAdvanced reading
- Tuple unpacking and extra values — unpack tuples and strings, and collect extra values with a star.
- Loop with index and value — unpack each position and item from
enumerate(). - Loop over lists together — unpack pairs from two lists with
zip().