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:

x = x + 5

You can use a compound operator:

x += 5

These are very handy in loops, data preprocessing, training steps in machine learning, and working with counters.

Syntax Overview

Operator
Meaning
Equivalent to

+=

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

In Machine Learning: Used when summing up loss during training.

2. -= Subtract and Assign

ML Use: Can be used in learning rate schedules:

3. *= Multiply and Assign

ML Use: Common in backpropagation when scaling gradients:

4. /= Divide and Assign

ML Use: Used to calculate averages (e.g. average loss):

5. //= Floor Division and Assign

ML Use: Used to compute how many batches we can get from a dataset.

6. %= Modulo and Assign

ML Use: Useful when running actions every N steps:

7. **= Power and Assign

ML 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

Compound Operator
Meaning
Example (x = 4, y = 2)
Result

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