Python Encyclopedia for Academics
  • Course Outline
  • Artificial Intelligence
    • Data Science Foundation
      • Python Programming
        • Introduction and Basics
          • Variables
          • Print Function
          • Input From User
          • Data Types
          • Type Conversion
        • Operators
          • Arithmetic Operators
          • Relational Operators
          • Bitwise Operators
          • Logical Operators
          • Assignment Operators
          • Compound Operators
          • Membership Operators
          • Identity Operators
      • Numpy
        • Vectors, Matrix
        • Operations on Matrix
        • Mean, Variance, and Standard Deviation
        • Reshaping Arrays
        • Transpose and Determinant of Matrix
      • Pandas
        • Series and DataFrames
        • Slicing, Rows, and Columns
        • Operations on DataFrames
        • Different wayes to creat DataFrame
        • Read, Write Operations with CSV files
      • Matplotlib
        • Graph Basics
        • Format Strings in Plots
        • Label Parameters, Legend
        • Bar Chart, Pie Chart, Histogram, and Scatter Plot
  • Machine Learning Algorithms
    • Regression Analysis In ML
      • Regression Analysis in Machine Learning
      • Proof of Linear Regression Formulas
      • Simple Linear Regression Implementation
      • Multiple Linear Regression
      • Advertising Dataset Example
      • Bike Sharing Dataset
      • Wine Quality Dataset
      • Auto MPG Dataset
    • Classification Algorithms in ML
      • Proof of Logistic Regression
      • Simplified Mathematical Proof of SVM
      • Iris Dataset
  • Machine Learning Laboratory
    • Lab 1: Titanic Dataset
      • Predicting Survival on the Titanic with Machine Learning
    • Lab 2: Dow Jones Index Dataset
      • Dow Jones Index Predictions Using Machine Learning
    • Lab 3: Diabetes Dataset
      • Numpy
      • Pandas
      • Matplotlib
      • Simple Linear Regression
      • Simple Non-linear Regression
      • Performance Matrix
      • Preprocessing
      • Naive Bayes Classification
      • K-Nearest Neighbors (KNN) Classification
      • Decision Tree & Random Forest
      • SVM Classifier
      • Logistic Regression
      • Artificial Neural Network
      • K means Clustering
    • Lab 4: MAGIC Gamma Telescope Dataset
      • Classification in ML-MAGIC Gamma Telescope Dataset
    • Lab 5: Seoul Bike Sharing Demand Dataset
      • Regression in ML-Seoul Bike Sharing Demand Dataset
    • Lab 6: Medical Cost Personal Datasets
      • Predict Insurance Costs with Linear Regression in Python
    • Lab 6: Predict The S&P 500 Index With Machine Learning And Python
      • Predict The S&P 500 Index With Machine Learning And Python
  • Artificial Neural Networks
    • Biological Inspiration vs. Artificial Neurons
    • Review linear algebra and calculus essentials for ANNs
    • Activation Function
  • Mathematics
    • Pre-Calculus
      • Factorials
      • Roots of Polynomials
      • Complex Numbers
      • Polar Coordinates
      • Graph of a Function
    • Calculus 1
      • Limit of a Function
      • Derivative of Function
      • Critical Points
      • Indefinite Integrals
  • Calculus 2
    • 3D Coordinates and Vectors
    • Vectors and Vector Operations
    • Lines and Planes in Space (3D)
    • Partial Derivatives
    • Optimization Problems (Maxima/Minima) in Multivariable Functions
    • Gradient Vectors
  • Engineering Mathematics
    • Laplace Transform
  • Electrical & electronics Eng
    • Resistor
      • Series Resistors
      • Parallel Resistors
    • Nodal Analysis
      • Example 1
      • Example 2
    • Transient State
      • RC Circuit Equations in the s-Domain
      • RL Circuit Equations in the s-Domain
      • LC Circuit Equations in the s-Domain
      • Series RLC Circuit with DC Source
  • Computer Networking
    • Fundamental
      • IPv4 Addressing
      • Network Diagnostics
  • Cybersecurity
    • Classical Ciphers
      • Caesar Cipher
      • Affine Cipher
      • Atbash Cipher
      • Vigenère Cipher
      • Gronsfeld Cipher
      • Alberti Cipher
      • Hill Cipher
Powered by GitBook
On this page
  • What are Compound Operators?
  • Syntax Overview
  • Step-by-Step Guide with Examples
  • Summary Table: Quick Reference
  • Keywords
  1. Artificial Intelligence
  2. Data Science Foundation
  3. Python Programming
  4. Operators

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

x = 10
x += 5  # same as x = x + 5
print(x)  # Output: 15

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

total_loss = 0
for loss in batch_losses:
    total_loss += loss

2. -= Subtract and Assign

accuracy = 100
accuracy -= 2
print(accuracy)  # Output: 98

ML Use: Can be used in learning rate schedules:

learning_rate = 0.1
learning_rate -= 0.01

3. *= Multiply and Assign

scale = 3
scale *= 2
print(scale)  # Output: 6

ML Use: Common in backpropagation when scaling gradients:

gradient *= momentum_factor

4. /= Divide and Assign

total = 100
total /= 4
print(total)  # Output: 25.0

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

average_loss = total_loss
average_loss /= len(batch)

5. //= Floor Division and Assign

samples = 101
samples //= 10
print(samples)  # Output: 10

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

6. %= Modulo and Assign

epoch = 5
epoch %= 2
print(epoch)  # Output: 1

ML Use: Useful when running actions every N steps:

if step % 10 == 0:
    print("Logging progress")

7. **= Power and Assign

base = 2
base **= 3
print(base)  # Output: 8

ML Use: Can be used to implement learning rate decay:

lr_decay = 0.95
learning_rate *= lr_decay ** epoch

8. Bitwise Compound Operators (advanced but useful)

&= Bitwise AND

a = 6  # binary 110
a &= 3  # binary 011
print(a)  # Output: 2 (binary 010)

|= Bitwise OR

a = 4
a |= 1
print(a)  # Output: 5

^= Bitwise XOR

a = 5
a ^= 3
print(a)  # Output: 6

<<= Left Shift

a = 2
a <<= 1
print(a)  # Output: 4

>>= Right Shift

a = 4
a >>= 1
print(a)  # Output: 2

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

PreviousAssignment OperatorsNextMembership Operators

Last updated 2 months ago