← Python lessons

Unpacking Values

Unpacking pulls several values out of a list into named variables in a single line — much easier to read than indexing each position by hand.

The idea

Instead of reading each position separately:

rolls = [3, 5, 2]
first = rolls[0]
second = rolls[1]
third = rolls[2]

do it all at once:

rolls = [3, 5, 2]
first, second, third = rolls
print(first, second, third)

Names on the left, a list of the same length on the right. first gets 3, second gets 5, third gets 2. Each name says what the value means, which reads better than rolls[0] and rolls[1] scattered through your code.

The counts must match

If there are three names on the left, the list needs exactly three items — otherwise Python raises a ValueError. Try editing the list below and running it to see that happen:

a, b = [10, 20]
print(a)
print(b)

See also: Lists, Variables.

Your turn

Add two lines: unpack rolls into first, second, and third, then print second.

rolls = [4, 6, 1]
# add two lines: unpack, then print the middle value

Expected output

6

Practise this in the free Python course, where every exercise checks your code instantly.