Compound Operators
Nerd Cafe
What are Compound Operators?
A compound operator is a shortcut for performing an operation and assignment in one step.
Instead of writing:
You can use a compound operator:
These are very handy in loops, data preprocessing, training steps in machine learning, and working with counters.
Syntax Overview
+=
Add and assign
x = x + y
-=
Subtract and assign
x = x - y
*=
Multiply and assign
x = x * y
/=
Divide and assign
x = x / y
//=
Floor divide and assign
x = x // y
%=
Modulo and assign
x = x % y
**=
Power and assign
x = x ** y
&=
Bitwise AND and assign
x = x & y
`
=`
Bitwise OR and assign
^=
Bitwise XOR and assign
x = x ^ y
>>=
Bitwise right shift
x = x >> y
<<=
Bitwise left shift
x = x << y
Step-by-Step Guide with Examples
1. +=
Add and Assign
+=
Add and AssignIn Machine Learning: Used when summing up loss during training.
2. -=
Subtract and Assign
-=
Subtract and AssignML Use: Can be used in learning rate schedules:
3. *=
Multiply and Assign
*=
Multiply and AssignML Use: Common in backpropagation when scaling gradients:
4. /=
Divide and Assign
/=
Divide and AssignML Use: Used to calculate averages (e.g. average loss):
5. //=
Floor Division and Assign
//=
Floor Division and AssignML Use: Used to compute how many batches we can get from a dataset.
6. %=
Modulo and Assign
%=
Modulo and AssignML Use: Useful when running actions every N steps:
7. **=
Power and Assign
**=
Power and AssignML Use: Can be used to implement learning rate decay:
8. Bitwise Compound Operators (advanced but useful)
&=
Bitwise AND
|=
Bitwise OR
^=
Bitwise XOR
<<=
Left Shift
>>=
Right Shift
Summary Table: Quick Reference
x += y
Addition
x += 2
6
x -= y
Subtraction
x -= 2
2
x *= y
Multiplication
x *= 2
8
x /= y
Division
x /= 2
2.0
x //= y
Floor Division
x //= 2
2
x %= y
Modulo
x %= 2
0
x **= y
Power
x **= 2
16
Keywords
compound operators
, Python
, assignment operators
, augmented assignment
, arithmetic operators
, machine learning
, data preprocessing
, training loop
, +=
, -=
, *=
, /=
, //=
, **=
, %=
, bitwise operators
, performance optimization
, learning rate decay
, gradient update
, Python syntax
, nerd cafe
Last updated