Augmented Assign Statement¶
In Python, we often write things like:
i = i + 1
There’s a convenient shorthand for this called the augmented assign statement:
i += 1
This is called the “augmented assign statement.”
Note that you cannot use the augmented assign statement with parallel or serial assigment, although you can use it for assignment to subscriptions or slices.
Mutable vs. Immutable Augmented Assign¶
The behavior of the augmented assign statement is quite different depending on whether it is an immutable or mutable object.
a = b = (1,)
a *= 3
# a is (1, 1, 1)
# b is still (1,)
c = d = [1]
c *= 3
# c and d are both [1, 1, 1]
Variables referring to immutables will be changed. They will be assigned to the result of the operation applied to the value. This is why a and b are different.
Variables referring to mutables will not be changed. Instead, the mutable is changed to reflect the result of the operation applied to the value. This is why c and d are the same.
You can see why I waited until now to introduce the augmented assign statement. It’s a fairly advanced topic requiring knowledge of mutables and immutables.
A Table of Operators¶
Let’s investigate each of the augmented assign “operators”:
+=
: - int, float, complex: Addition - tuple, frozenset, str, bytes: Concatenation - list, bytearray: in-place concatenation-=
: - int, float, complex: Subtraction - frozenset: Set difference - set: In-place set-difference*=
: - int, float, complex: Multiplication - tuple, str, bytes: Duplication. - list, bytearray: in-place duplication.@=
: - No built-in Python type uses this. It is used for matrix multiplication orsimilar in other libraries.
/=
: - int, float, complex: Division//=
: - int, float: Int Division%=
: - int, float: Int Remainder (mod) - str, bytes, bytearray: Printf formatting**=
: - int, float, complex: Exponents.>>=
: - int: Right shift. (a >>= i
is the same asa //= 2**i
)<<=
: - int: Left shift. (a <<= i
is the same asa *= 2**i
)&=
: - int: bit-wise and - frozenset: Set intersection - set: In-place set intersection^=
: - int: bit-wise xor - frozenset: Set symmetric difference - set: In-place set symmetric difference|=
: - int: bit-wise or - frozenset: Set union - set: In-place set union
Notes on Usage¶
Augmented assign is often just a shortcut for more complicated behavior.
I try to avoid using it unless it’s really clear what it is doing.
The behavior with mutable objects is often intentional yet surprising to newer Python programmers. For this reason, I like to add a comment explaining that it is an in-place operation.