Sub topic 14
Assignment and augmented assignment
This chapter assumes you can run Python scripts, know the core built-in types (int, float, str, list, dict), and have used simple assignment like x = 3. It covers what assignment does, the forms it takes, and how += and the other augmented operators differ from writing out x = x + 1.
Assignment binds names
An assignment statement does not copy a value into a box. It makes a name refer to an object. The right side is evaluated first, then the name is bound to the result.
Assignment in Python is a statement, not an expression, so print(x = 3) is a syntax error and if x = 3: is rejected. The walrus operator :=, covered in a later chapter, is the expression form.
Because names are references, two names can point at one object:
a = b = []
a.append(1)
print(b)
x, y = 1, 2
x, y = y, x
print(x, y)
first, *rest = [1, 2, 3, 4]
print(first, rest)This prints [1], then 2 1, then 1 [2, 3, 4].
- Chained assignment (
a = b = []) evaluates the right side once and binds every name to that same object. Both names share one list. - Tuple unpacking (
x, y = y, x) evaluates the whole right side into a tuple first, then assigns left to right. That is why the swap needs no temporary variable. - Starred targets (
first, *rest) collect the leftover items into a new list.
The number of targets must match the number of values, unless a starred target absorbs the difference. Otherwise Python raises ValueError.
What augmented assignment does
An augmented assignment combines a binary operator with assignment. x += 1 is close to x = x + 1, but there are two differences:
- The target is evaluated only once.
- Python first tries an in-place method (such as
__iadd__). If the type does not provide one, it falls back to the ordinary operator (__add__) and rebinds the name.
Every arithmetic and bitwise binary operator has an augmented form:
| Augmented form | Plain operator | In-place method | Column | Column |
|---|---|---|---|---|
| `x += y` | `+` | `__iadd__` | ||
| `x -= y` | `-` | `__isub__` | ||
| `x *= y` | `*` | `__imul__` | ||
| `x /= y` | `/` | `__itruediv__` | ||
| `x //= y` | `//` | `__ifloordiv__` | ||
| `x %= y` | `%` | `__imod__` | ||
| `x **= y` | `**` | `__ipow__` | ||
| `x &= y`, `x \ | = y`, `x ^= y` | `&`, `\ | `, `^` | `__iand__`, `__ior__`, `__ixor__` |
| `x <<= y`, `x >>= y` | `<<`, `>>` | `__ilshift__`, `__irshift__` |
The matrix form @= also exists. The plain operators keep their usual types, so n = 10; n /= 2 leaves n as the float 5.0.
The last step matters: even after an in-place method runs, Python still binds the target to whatever the method returned. For lists, that is the same object, so the binding changes nothing visible.
Immutable and mutable objects behave differently
For immutable types such as int, str and tuple, there is no in-place method, so += builds a new object and rebinds the name. Other names that referred to the old object are unaffected.
For a mutable type like list, += calls list.__iadd__, which extends the existing list. Every name that refers to that list sees the change.
n = 5
m = n
n += 1
print(n, m)
a = [1, 2]
b = a
a += [3]
print(b)
print(a is b)
a = a + [4]
print(b)
print(a is b)The output is 6 5, [1, 2, 3], True, [1, 2, 3], False.
After a += [3], b changed because both names still refer to one list. After a = a + [4], a refers to a new list and b keeps the old one.
A second difference for lists: += accepts any iterable, while + requires another list.
a = [1]
a += "hi"
print(a)
try:
a = a + "hi"
except TypeError:
print("TypeError")
s = "ab"
s *= 2
print(s)This prints [1, 'h', 'i'], then TypeError, then abab. The string "hi" is iterated character by character, which often surprises people who meant to append one string item.
The target is evaluated once
With a subscript or attribute target, x[i] += 1 looks up x and i once. This matters when evaluating the target has side effects:
def key():
print("key called")
return "a"
d = {"a": 1}
d[key()] += 1
print(d)key called prints once, then {'a': 2}. Writing d[key()] = d[key()] + 1 would call key() twice.
Common errors
Augmented assignment makes the name local
Inside a function, any assignment to a name, including +=, makes that name local to the function. Reading a global counter with += therefore fails:
count = 0
def bump():
count += 1
try:
bump()
except UnboundLocalError:
print("UnboundLocalError")Python sees count += 1 as count = count + 1, treats count as local, and finds it has no value yet. Fix it by declaring global count (or nonlocal for an enclosing function), or better, by passing the value in and returning the result.
Augmented assignment on an item inside a tuple
A tuple cannot be changed, but it can hold a mutable object. t[0] += [9] first extends the list in place, then tries to rebind t[0], which fails:
t = ([1], 2)
try:
t[0] += [9]
except TypeError as e:
print(e)
print(t)The error is 'tuple' object does not support item assignment, yet t is now ([1, 9], 2). The statement raised an error and still changed the data. If you need to mutate the inner list, call t[0].extend([9]), which involves no rebinding.
Unintended sharing with chained assignment
a = b = [] is fine for immutable values such as a = b = 0, because rebinding one name never affects the other. With mutable values it creates one shared object. Use separate statements (a = [] and b = []) when each name needs its own container.
Choosing between the forms
- Use
x += yfor counters, running totals and building up a list in one place. It is shorter, and it evaluates the target once. - Use
x = x + ywhen you want a new object and must not disturb other references. - Use unpacking assignment for swaps and for splitting sequences, and chained assignment only for immutable values.
- Custom classes can define
__iadd__and the other in-place methods. If you leave them out,+=still works through__add__, and the name is rebound to the new result.
Exercise
After running the code below, what do a, b and c contain, and why?
a = [1]
b = a
c = a.copy()
b += [2]
c += [3]
a = a + [4]
Show answer
b is the same list object as the original a, so b += [2] extends it in place, giving [1, 2]. c is a separate copy, so c += [3] makes it [1, 3]. The last line builds a new list [1, 2, 4] and rebinds a to it, so a is [1, 2, 4], b stays [1, 2], and c is [1, 3].
Exercise
Why does the function below raise UnboundLocalError, and how would you fix it without using global?
total = 10
def add(n):
total += n
return total
Show answer
The += assigns to total, which makes total a local name inside add, and the local has no value when it is read. Fix it by using a different local name, for example def add(n, total): return total + n, or def add(n): result = total + n; return result, so the function reads the global without assigning to it.