Chapters
Python114 chapters

BasicsChapter 7 of 114

Multiple Assignment

Assign several names at once, unpack a sequence, and swap without a temporary.

Several names, several values

Python can assign a row of names from a row of values in one line:

Python
x, y, z = 1, 2, 3
print(x, y, z)

Output

1 2 3

The counts have to match. Three names need three values, or Python raises ValueError.

Unpacking a sequence

The values do not have to be written out. Any sequence of the right length works:

Python
point = (4, 9)
x, y = point
print(x, y)

first, second, third = "abc"
print(first, second, third)

Output

4 9
a b c

This is why looping over pairs reads so cleanly, which comes up again when you get to dictionaries.

Swapping

In most languages swapping two variables needs a third. In Python the whole right-hand side is built before anything is assigned, so it does not:

Python
a = "left"
b = "right"
a, b = b, a
print(a, b)

Output

right left

The star catches the rest

Put * in front of one name and it collects everything the other names do not take. It always ends up a list:

Python
first, *rest = [10, 20, 30, 40]
print(first)
print(rest)

head, *middle, tail = [1, 2, 3, 4, 5]
print(head, middle, tail)

Output

10
[20, 30, 40]
1 [2, 3, 4] 5

One value, several names

Chained assignment points every name at the same value:

Python
a = b = c = 0
print(a, b, c)

Output

0 0 0
Python
a = b = []
a.append("added through a")
print(b)

Output

['added through a']

Ignoring a value

By convention a single underscore means "I have to name this, but I do not care about it":

Python
_, wanted, _ = ("skip", "keep", "also skip")
print(wanted)

Output

keep

Test yourself

2 questions

What does a, b = b, a do?

Show the answer

Swaps them, because the right side is built before anything is assigned — The right-hand side becomes a tuple first, then it is unpacked into the names.

After first, *rest = [10, 20, 30], what is rest?

Show the answer

[20, 30] — A starred name collects whatever the others do not take, and it is always a list.

Next chapter

Global Variables

Names defined outside a function, and the keyword you need to change one.