Sub topic 14
Assignment and augmented assignment
This chapter assumes you can run Python scripts or use the REPL. It also assumes you know the core types (int, float, str, list, dict) and how to bind a name with x = 5. Here we look at what assignment does, how augmented assignment such as += differs from x = x + 1, and where this trips people up.
Assignment is a statement, not an expression
In Python, = binds a name to an object. It is a statement, so it has no value and cannot sit inside another expression. That is why if x = 3: is a syntax error. The walrus operator := is the expression form, covered in a later chapter.
You can bind several names in one statement:
a = b = 0 # both names refer to the same object
x, y = 1, 2 # tuple unpacking
x, y = y, x # swap without a temporary variable
first, *rest = [10, 20, 30]
print(a, b, x, y, first, rest)Python evaluates the whole right-hand side before it binds any name. That is why the swap works.
Augmented assignment
An augmented assignment combines an operator with assignment. total += 3 is close to total = total + 3. Every arithmetic and bitwise operator has an augmented form.
| Form | Meaning | Column |
|---|---|---|
| `x += y` | add | |
| `x -= y` | subtract | |
| `x *= y` | multiply | |
| `x /= y` | true divide | |
| `x //= y` | floor divide | |
| `x %= y` | modulo | |
| `x **= y` | power | |
| `x &= y`, `x \ | = y`, `x ^= y` | bitwise and, or, xor |
| `x <<= y`, `x >>= y` | shifts |
total = 0
for item in [3, 1, 4]:
total += item
print(total)
count = 17
count //= 5
print(count)
count **= 2
print(count)The difference: in-place versus rebinding
The two forms differ in one way. x += y evaluates x only once. For mutable objects, it first tries the in-place method (__iadd__). If the type has no in-place method, Python falls back to x = x + y.
Lists define __iadd__, so += changes the existing list. Strings and tuples are immutable, so += builds a new object and rebinds the name.
a = [1, 2]
b = a
a += [3] # mutates the shared list
print(b) # [1, 2, 3]
c = [1, 2]
d = c
c = c + [3] # builds a new list and rebinds c
print(d) # [1, 2]
s = "ab"
t = s
s += "c"
print(t) # abCommon errors
- Using an augmented assignment on a name that does not exist yet.
counter += 1raisesNameError(orUnboundLocalErrorinside a function) because Python must read the old value first. - Assigning to a name inside a function and expecting it to change a global. The assignment makes the name local unless you declare
global. - Writing
a = b = []and expecting two separate lists. Both names refer to the same list.
Exercise
What do a and b print after this code runs, and why?
a = [1]
b = a
a += [2]
a = a + [3]
print(a)
print(b)
Show answer
a prints [1, 2, 3] and b prints [1, 2]. The += mutates the shared list in place, so b sees [1, 2]. Then a = a + [3] builds a new list and rebinds only a, so b keeps [1, 2].