7.3 Assignment Operators
The augmented assignment operators — += -= *= /= //= %= **= &= |= ^= <<= >>= — as shorthand for combining an operation with assignment in one step.
=
Plain assignment binds a name to a value — already covered in 4.8 Variables and 6.4 Assignment Operations.
>>> x = 5
>>> x
5
Augmented Assignment
What Is It?
Shorthand combining an arithmetic/bitwise operation with assignment in one step — x += 1 means x = x + 1.
Why Is It Used?
Less repetition, and the intent (“update this variable”) is clearer at a glance.
| Operator | Equivalent To | Example (starting x=5) |
Result |
|---|---|---|---|
+= |
x = x + n |
x += 3 |
8 |
-= |
x = x - n |
x -= 2 (from 8) |
6 |
*= |
x = x * n |
x *= 2 (from 6) |
12 |
/= |
x = x / n |
x /= 4 (from 12) |
3.0 |
//= |
x = x // n |
x //= 3 (10 ->) |
3 |
%= |
x = x % n |
x %= 2 (from 3) |
1 |
**= |
x = x ** n |
x **= 4 (2 ->) |
16 |
&= |
x = x & n |
x &= 3 (5 ->) |
1 |
|= |
x = x | n |
x |= 2 (5 ->) |
7 |
^= |
x = x ^ n |
x ^= 1 (5 ->) |
4 |
<<= |
x = x << n |
x <<= 3 (1 ->) |
8 |
>>= |
x = x >> n |
x >>= 2 (16 ->) |
4 |
Quick Interview Answer
“Augmented assignment operators like
+=,-=,*=combine an operation with assignment in one step —x += 3is shorthand forx = x + 3. They exist for both arithmetic (+= -= *= /= //= %= **=) and bitwise operators (&= |= ^= <<= >>=). For an immutable value like anint,x += 1rebindsxto a new object; for a mutable value like alist,x += [4]mutates the existing object in place via__iadd__— the same rebind-vs-mutate distinction covered in 6.4 Assignment Operations.”
Common Mistakes
- Assuming
x += 1always mutates in place — for immutable types it rebinds to a new object, which only matters when another variable shares the old reference. - Chaining augmented assignment across unrelated statements and losing track of the running value — prefer clear, separate steps when the sequence isn’t obvious at a glance.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form