Sub topic 7
Multiple assignment, unpacking, and augmented assignment
This chapter assumes you know that an assignment binds a name to an object, that int, str, and list are different types, and that strings and numbers are immutable while lists are mutable. Here you will use those facts to read and write compact assignment statements correctly and to spot where they behave unexpectedly.
Chained assignment
Chained assignment binds several names to one object in a single statement:
a = b = 0
a += 1
print(a, b)
x = y = []
x.append("shared")
print(y)
print(x is y)The first part prints 1 0. Both names start out bound to the same 0. Then a += 1 rebinds a to a new integer, and b is unaffected. The second part prints ['shared'] and True. x and y name one list, so a mutation through either name is visible through the other.
Chained assignment is safe for immutable values such as numbers, strings, and None. Do not use it to create separate empty lists or dictionaries. Write x = [] and y = [] on separate lines instead.
Packing and unpacking
A comma-separated sequence of expressions builds a tuple. This is called packing, and the parentheses are optional. Unpacking is the reverse: the names on the left receive the items on the right, in order.
point = 3, 4
print(point)
x, y = point
print(x, y)
r, g, b = "xyz"
print(r, g, b)
for index, (name, score) in enumerate([("Ada", 90), ("Linus", 85)]):
print(index, name, score)The right side can be any iterable: a tuple, a list, a string, a range, or a generator. The left side can be nested, as in (name, score) above. The structure of the names must match the structure of the data.
Count mismatches
The number of names must equal the number of items, or Python raises ValueError:
try:
a, b = [1, 2, 3]
except ValueError as e:
print(e)
try:
a, b, c = (1, 2)
except ValueError as e:
print(e)The messages are too many values to unpack (expected 2) and not enough values to unpack (expected 3, got 2). These errors usually mean a function returned a different shape than you assumed. They are useful because they fail at the assignment instead of letting a wrong value travel further.
Swapping without a temporary
The right side of an assignment is fully evaluated before any target is assigned. This is why the swap idiom works:
a, b = 1, 2
a, b = b, a
print(a, b)
# Fibonacci step: both new values use the old a and b
a, b = 0, 1
for _ in range(6):
a, b = b, a + b
print(a)This prints 2 1 and then 8. No value is copied between boxes. Python builds the tuple (b, a) from the two objects, then rebinds each name.
Targets are bound left to right, one at a time. This matters when a later target depends on an earlier one:
nums = [0, 0, 0]
i = 0
i, nums[i] = 1, 9
print(i, nums)This prints 1 [0, 9, 0]. By the time nums[i] is evaluated, i is already 1. Avoid writing assignments like this, because readers will misjudge them.
Star unpacking
One target may carry a leading *. It collects whatever items the other names did not take, and it always receives a list:
first, *middle, last = [1, 2, 3, 4, 5]
print(first, middle, last)
head, *tail = "abc"
print(head, tail)
a, *rest = [10]
print(a, rest)
*init, final = (7, 8, 9)
print(init, final)The output is 1 [2, 3, 4] 5, then a ['b', 'c'], then 10 [], then [7, 8] 9. The starred target can be empty, and it is a list even when the source is a tuple or a string. You can use only one starred target per assignment, because with two the split would be ambiguous.
A single underscore is the conventional name for a value you do not need:
_, year, _ = ("Ada", 1815, "London")
print(year)_ is an ordinary name and gets bound like any other. The convention only tells readers to ignore it.
Augmented assignment
An augmented assignment combines an operator with binding. n += 1 is similar to n = n + 1, but the target is evaluated only once, and mutable types may handle it differently.
| Statement | Operator used | Notes |
|---|---|---|
| `n += 2` | `+` | Also concatenates strings and lists |
| `n -= 2` | `-` | |
| `n *= 2` | `*` | Repeats strings and lists |
| `n /= 2` | `/` | Result is always a float |
| `n //= 2` | `//` | Floor division |
| `n %= 2` | `%` | Modulo |
| `n **= 2` | `**` | Exponentiation |
n = 10
n /= 4
print(n)
n //= 2
print(n)
n **= 3
print(n)
s = "ab"
s *= 3
print(s)This prints 2.5, 1.0, 1.0, and ababab. Note that n became a float after /= and stayed one. Augmented assignment rebinds the name, so the type of the name's object can change.
In-place behavior depends on mutability
For immutable types, += creates a new object and rebinds the name. For a list, += extends the existing object in place, which affects every name bound to it:
n = 5
m = n
n += 1
print(n, m)
a = [1, 2]
b = a
a += [3]
print(a, b)
a = a + [4]
print(a, b)This prints 6 5, then [1, 2, 3] [1, 2, 3], then [1, 2, 3, 4] [1, 2, 3]. a += [3] mutated the shared list, so b saw the change. a = a + [4] built a new list and rebound only a.
The tuple gotcha
Augmented assignment always ends with a binding step. If the target is an item of a tuple, that step fails, even when the in-place change has already happened:
t = ([1], 2)
try:
t[0] += [5]
except TypeError as e:
print(e)
print(t)This prints 'tuple' object does not support item assignment, followed by ([1, 5], 2). The list was extended in place, and then Python tried to store the result back into the tuple. The statement raised an error but still changed the data. To avoid this, call t[0].extend([5]) instead.
Common errors
- Using chained assignment with a mutable value and expecting independent objects.
- Unpacking a result without checking its length, then getting a
ValueError. - Forgetting that a starred target is always a list, not a tuple or string.
- Assuming
x += yis identical tox = x + yfor lists and other mutable types. - Writing assignments in which a later target depends on an earlier one, such as
i, nums[i] = .... - Using an augmented operator on a name that does not exist yet.
total += 1raisesNameErroriftotalwas never bound.
Exercise
Predict the output of this code, then explain the last line. a = [1, 2] b = a c = a + [3] a += [4] print(a, b, c) print(a is b, a is c)
Show answer
It prints [1, 2, 4] [1, 2, 4] [1, 2, 3] and then True False. c = a + [3] builds a new list, so c is separate and never sees the later change. a += [4] extends the original list in place. Since b names that same list, b shows the change, and a is b is True. a is c is False because c is a different object.
Exercise
Given record = ("Ada", 1815, "mathematician", "London", "UK"), write one unpacking statement that binds name to the first item, place to the last item, and details to a list of everything in between. What are the values?
Show answer
name, *details, place = record. Then name is 'Ada', details is [1815, 'mathematician', 'London'], and place is 'UK'. The starred target is a list even though record is a tuple.
Exercise
What does this code print, and why does the first print show a different list than you might expect from reading t[0] += [5] as a failed statement?
t = ([1], 2)
try:
t[0] += [5]
except TypeError:
print("error")
print(t)
Show answer
It prints error and then ([1, 5], 2). The += on the list inside the tuple extends that list in place, which succeeds. Python then tries to bind the result back to t[0], and tuples do not allow item assignment, so it raises TypeError. The error occurs after the mutation, so the list is already changed.