Table of Contents
Toggle
The fundamental assignment operator (=) in Python serves as the foundation for variable assignment. Unlike mathematical equality, it assigns values from right to left:
x = 10 # Assigns integer 10 to variable x
y = 5.5 # Assigns float 5.5 to variable y
z = x + y # Assigns sum of x and y to z
a = 10
a += 5 # Equivalent to a = a + 5
print(a) # Output: 15
b = 5
b *= 3 # Equivalent to b = b * 3
print(b) # Output: 15
Augmented operators automatically handle type conversion:
num = 10 # int
num += 5.5 # converts to float
print(num) # Output: 15.5
x = 20
x -= 5 # x = 15
y = 10
y /= 2 # y = 5.0
z = 25
z %= 7 # z = 4
Assignment operators in Python are the building blocks for working with variables. They not only assign values but also allow performing mathematical and logical operations more concisely using augmented assignment operators. In this guide, we’ll cover the basics, advanced usage, and best practices.
The simple = operator is used to assign a value to a variable. It works from right to left:
x = 10 # Assigns integer 10
y = 5.5 # Assigns float 5.5
z = x + y # z becomes 15.5
Note: This is not mathematical equality. It simply stores values in memory.
Augmented assignment operators combine arithmetic or bitwise operations with assignment. They make code shorter, faster, and more readable.
a = 10
a += 5 # Equivalent to a = a + 5
print(a) # Output: 15
x = 20
x -= 7 # Equivalent to x = x - 7
print(x) # Output: 13
b = 4
b *= 3 # Equivalent to b = b * 3
print(b) # Output: 12
y = 10
y /= 2 # Equivalent to y = y / 2
print(y) # Output: 5.0
z = 25
z %= 7 # Equivalent to z = z % 7
print(z) # Output: 4
a = 17
a //= 3 # Equivalent to a = a // 3
print(a) # Output: 5
p = 2
p **= 3 # Equivalent to p = p ** 3
print(p) # Output: 8
n = 10
n &= 7 # Bitwise AND
print(n) # Output: 2
m = 5
m <<= 2 # Left shift
print(m) # Output: 20
Augmented operators often convert types automatically. For example, when adding an int and float:
num = 10 # int
num += 5.5 # int + float → float
print(num) # Output: 15.5
Warning: Be cautious with /= as it always converts result to float.
✅ Advantages
❌ Common Pitfalls
= with == (assignment vs comparison)Assignment operators are the foundation of Python programming. By mastering both basic and augmented operators, you can write code that is cleaner, faster, and easier to maintain. Always watch out for type conversions and remember to use these operators wisely for best performance.
Next Up: Python Comparison Operators ⚖️
