Sub topic 7
Multiple assignment, unpacking, and augmented assignment
This chapter assumes you know that an assignment binds a name to an object, and that you can use the arithmetic operators. It covers three shortcuts that make assignment shorter: assigning several names at once, unpacking a sequence into names, and updating a value in place with operators such as +=.
Assigning several names at once
You can give one object several names with a chained assignment. You can also bind several names to several objects in one statement.
a = b = 0
x, y = 1, 2
print(a, b, x, y)The right side of x, y = 1, 2 builds a tuple, and Python then unpacks it into the names on the left. This gives the standard swap idiom, which needs no temporary variable:
x, y = 1, 2
x, y = y, x
print(x, y)The whole right side is evaluated before any name is rebound. That is why the swap works.
Unpacking sequences
Unpacking works with any iterable, such as a list, tuple, or string. The number of names must match the number of items.
point = (3, 4)
px, py = point
first, second, third = "abc"
print(px, py, first, second, third)
try:
p, q = [1, 2, 3]
except ValueError as e:
print("ValueError:", e)A name with a star collects the leftover items into a list. This avoids the mismatch error when you only care about some of the items.
head, *tail = [10, 20, 30, 40]
print(head, tail)
first, *middle, last = range(1, 6)
print(first, middle, last)
_, value = ("ignored", 99)
print(value)By convention, _ names a value you do not plan to use. Only one starred name is allowed in a single unpacking target.
Augmented assignment
An augmented assignment combines an operator with assignment. total += 5 means roughly total = total + 5.
total = 10
total += 5
total -= 3
total *= 2
total //= 5
total **= 2
print(total)The same pattern exists for /=, %=, and for strings and lists as well.
label = "ab"
label += "c"
label *= 2
print(label)Rebinding versus mutating
For immutable objects such as int and str, += creates a new object and rebinds the name. For a mutable object such as a list, += changes the existing object in place. Every other name bound to that list sees the change.
n = 1
m = n
m += 1
print(n, m)
a = [1]
b = a
b += [2]
print(a, b, a is b)The integers end up different (1 2). The lists are the same object, so both print [1, 2] and a is b is True.
How a swap evaluates
Exercise
What do a, b, and rest hold after a, *rest, b = [1, 2, 3, 4], and what does s hold after s = "hi"; s += "!"; s *= 2?
Show answer
a is 1, b is 4, and rest is the list [2, 3]. The string s is "hi!hi!". Each += or *= on a string builds a new string and rebinds s.