Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

⚡ Python Shorthand Assignment Operators: Complete Guide

Python Shorthand Assignment Operators - Complete Guide

Shorthand assignment operators let you write cleaner, more efficient Python code.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
📑 On this page:
  • What are Shorthand Assignment Operators?
  • Quick Reference Table
  • Addition Assignment (+=)
  • Subtraction Assignment (-=)
  • Multiplication Assignment (*=)
  • Division Assignment (/=)
  • Modulus Assignment (%=)
  • Floor Division Assignment (//=)
  • Exponentiation Assignment (**=)
  • Bitwise Shorthand Operators
  • Real-World Examples
  • Common Mistakes to Avoid
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
📚 What You'll Learn Here
  • What shorthand assignment operators are — shortcuts for updating variables
  • Addition Assignment (+=) — add and assign in one step
  • Subtraction Assignment (-=) — subtract and assign
  • Multiplication Assignment (*=) — multiply and assign
  • Division Assignment (/=) — divide and assign
  • Modulus Assignment (%=) — remainder and assign
  • Floor Division Assignment (//=) — integer division and assign
  • Exponentiation Assignment (**=) — power and assign
  • Bitwise Shorthand Operators — &=, |=, ^=, >>=, <<=
  • Real-world examples — shopping cart, game score, banking
  • Common mistakes — and how to avoid them

What are Shorthand Assignment Operators?

Shorthand assignment operators (also called compound assignment operators) are shortcuts that let you perform an operation and assignment in a single step. Instead of writing x = x + 5, you can simply write x += 5.

💡 Key insight: Shorthand operators make your code cleaner, more readable, and slightly faster by modifying variables in place rather than creating new objects.

Think of them as "syntactic sugar" — they don't add new functionality, but they make your code more concise and professional. Once you start using them, you'll wonder how you ever wrote code without them!

Quick Reference Table

Here's a quick reference of all shorthand assignment operators:

Operator Example Equivalent To Description
+= x += 3 x = x + 3 Addition assignment
-= x -= 3 x = x - 3 Subtraction assignment
*= x *= 3 x = x * 3 Multiplication assignment
/= x /= 3 x = x / 3 Division assignment
%= x %= 3 x = x % 3 Modulus assignment
//= x //= 3 x = x // 3 Floor division assignment
**= x **= 3 x = x ** 3 Exponentiation assignment
&= x &= 3 x = x & 3 Bitwise AND assignment
|= x |= 3 x = x | 3 Bitwise OR assignment
^= x ^= 3 x = x ^ 3 Bitwise XOR assignment
>>= x >>= 1 x = x >> 1 Right shift assignment
<<= x <<= 1 x = x << 1 Left shift assignment

1. Addition Assignment (+=)

The addition assignment operator (+=) adds the right-hand value to the variable and assigns the result back. It's perfect for counters, accumulators, and building totals.

# Addition Assignment (+=)
count = 0
count += 1  # Same as: count = count + 1
print(count)  # Output: 1

total = 50
total += 10
print(total)  # Output: 60

2. Subtraction Assignment (-=)

The subtraction assignment operator (-=) subtracts the right-hand value from the variable and assigns the result back.

# Subtraction Assignment (-=)
lives = 5
lives -= 1  # Same as: lives = lives - 1
print(lives)  # Output: 4

score = 100
score -= 25
print(score)  # Output: 75

3. Multiplication Assignment (*=)

The multiplication assignment operator (*=) multiplies the variable by the right-hand value and assigns the result back.

# Multiplication Assignment (*=)
number = 10
number *= 2  # Same as: number = number * 2
print(number)  # Output: 20

price = 5.50
price *= 3
print(price)  # Output: 16.5

4. Division Assignment (/=)

The division assignment operator (/=) divides the variable by the right-hand value and assigns the result back. Note: This always returns a float in Python 3.

# Division Assignment (/=)
amount = 100
amount /= 4  # Same as: amount = amount / 4
print(amount)  # Output: 25.0

total = 50
total /= 3
print(total)  # Output: 16.666666666666668

5. Modulus Assignment (%=)

The modulus assignment operator (%=) divides the variable by the right-hand value and assigns the remainder back.

# Modulus Assignment (%=)
number = 17
number %= 5  # Same as: number = number % 5
print(number)  # Output: 2

x = 20
x %= 6
print(x)  # Output: 2

6. Floor Division Assignment (//=)

The floor division assignment operator (//=) performs floor division and assigns the result back.

# Floor Division Assignment (//=)
number = 17
number //= 5  # Same as: number = number // 5
print(number)  # Output: 3

x = 20
x //= 6
print(x)  # Output: 3

7. Exponentiation Assignment (**=)

The exponentiation assignment operator (**=) raises the variable to the specified power and assigns the result back.

# Exponentiation Assignment (**=)
number = 3
number **= 4  # Same as: number = number ** 4
print(number)  # Output: 81

x = 2
x **= 10
print(x)  # Output: 1024

8. Bitwise Shorthand Operators

Python also provides shorthand versions of bitwise operators:

&=

Bitwise AND assignment

|=

Bitwise OR assignment

^=

Bitwise XOR assignment

>>=

Right shift assignment

<<=

Left shift assignment

# Bitwise Shorthand Examples
a = 7   # Binary: 0111
b = 1

# Left Shift Assignment
a <<= b  # Same as: a = a << b
print(a)  # Output: 14 (1110 in binary)

# Right Shift Assignment
a = 7   # Binary: 0111
a >>= b  # Same as: a = a >> b
print(a)  # Output: 3 (0011 in binary)

# Bitwise AND Assignment
x = 7   # Binary: 0111
x &= 3  # Same as: x = x & 3
print(x)  # Output: 3

# Bitwise OR Assignment
y = 4   # Binary: 0100
y |= 3  # Same as: y = y | 3
print(y)  # Output: 7

9. Real-World Examples

🛒 Shopping Cart Total

# Shopping Cart Example
total = 0
items = [25.50, 10.00, 15.75]

for price in items:
    total += price  # Add each item price

print(f"Total: ${total:.2f}")

# Output:
# Total: $51.25

🎮 Game Score Tracker

# Game Score Example
score = 0
score += 10  # Player wins! Add 10 points
score *= 2   # Bonus round! Double the score
print(f"Final Score: {score}")

# Output:
# Final Score: 20

🏦 Banking Balance Update

# Banking Balance Example
balance = 1000
balance += 500  # Deposit ₹500
balance -= 200  # Withdrawal ₹200
print(f"Current Balance: ₹{balance}")

# Output:
# Current Balance: ₹1300

10. Common Mistakes to Avoid

❌ Mistake 1: Confusing += with =+

=+ is not a valid operator! Always write += (plus sign before equals).

# WRONG
x =+ 5  # This is actually x = +5 (not addition assignment!)

# CORRECT
x += 5  # This adds 5 to x

❌ Mistake 2: Using shorthand with uninitialized variables

You can't use += on a variable that hasn't been defined yet.

# WRONG
total += 10  # NameError: name 'total' is not defined

# CORRECT
total = 0
total += 10  # Now it works

❌ Mistake 3: Using shorthand with incompatible types

Works fine for strings with +=, but be careful with other types.

# This works (strings)
text = "Hello"
text += " World"
print(text)  # Output: Hello World

# This will cause an error
num = "10"
num += 5  # TypeError: can only concatenate str to str

Try It Yourself!

Experiment with shorthand assignment operators directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
SHORTHAND ASSIGNMENT OPERATORS
========================================

1. ADDITION ASSIGNMENT (+=)
x += 5: 15

2. SUBTRACTION ASSIGNMENT (-=)
y -= 3: 7

3. MULTIPLICATION ASSIGNMENT (*=)
z *= 3: 30

4. DIVISION ASSIGNMENT (/=)
a /= 3: 3.3333333333333335

5. MODULUS ASSIGNMENT (%=)
b %= 3: 1

6. FLOOR DIVISION ASSIGNMENT (//=)
c //= 3: 3

7. EXPONENTIATION ASSIGNMENT (**=)
d **= 4: 81

8. REAL-WORLD EXAMPLE (Banking)
Current Balance: ₹1300

✅ Shorthand operators make your code cleaner!
🏆

🎉 You've Mastered Python Shorthand Assignment Operators!

You understand all shorthand assignment operators (+=, -=, *=, /=, %=, //=, **=, &=, |=, ^=, >>=, <<=). These are essential for writing clean, efficient Python code.

Quick Quiz – Test Your Knowledge

Let's see what you've learned about shorthand assignment operators:

1. What is the result of x = 5; x += 3; print(x)?
2. What does x *= 2 mean?
3. What is the result of a = 7; a %= 2; print(a)?

Frequently Asked Questions

🤔 What's the difference between += and =+? ▼

+= is a compound assignment operator that adds and assigns. =+ is not a valid operator — Python interprets it as = + (assignment of a positive number).

🔧 Can I use shorthand operators with strings? ▼

Yes! += works with strings for concatenation: text = "Hello"; text += " World".

📐 Are shorthand operators faster? ▼

Yes! They modify variables in place rather than creating new objects, making them slightly faster and more memory-efficient.

📊 Can I chain shorthand operators? ▼

No, you can't chain shorthand operators like x += y += 5. Each operator must be used separately.

📚 Where to Go From Here

Now that you understand Python shorthand assignment operators, here are some related topics to explore:

📝 Assignment Operators

Review basic assignment operators

🔢 Arithmetic Operators

Learn about arithmetic operators

📊 Relational Operators

Learn about comparison operators

📖 Related Tutorials
  • Assignment Operators
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
📖 Interview & FAQ Resources
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: Assignment Operators Next: Relational Operators →