In Python, Assignment Operators are used to assign values to variables. While the basic assignment operator is the equals sign (=), Python provides a variety of compound assignment operators (also known as augmented assignment operators) that allow you to perform an arithmetic operation and an assignment in a single step.
Assignment operators act as a shorthand for updating the value of a variable based on its current value. For example, instead of writing x = x + 5, you can simply write x += 5.
| Operator | Example | Equivalent to | Description |
| = | x = 5 | x = 5 | Assigns the value on the right to the variable on the left. |
| += | x += 3 | x = x + 3 | Adds the right operand to the left and assigns the result. |
| -= | x -= 3 | x = x - 3 | Subtracts the right operand from the left and assigns the result. |
| *= | x *= 3 | x = x * 3 | Multiplies the left operand by the right and assigns the result. |
| /= | x /= 3 | x = x / 3 | Divides the left operand by the right and assigns the result (float). |
| //= | x //= 3 | x = x // 3 | Floor divides the left operand and assigns the integer result. |
| %= | x %= 3 | x = x % 3 | Takes the modulus and assigns the remainder. |
| **= | x **= 3 | x = x ** 3 | Performs exponentiation and assigns the result. |
Efficiency: It is slightly faster for the computer to process in certain contexts.
Readability: It reduces redundancy. You don't have to type the variable name twice.
Clean Code: It makes the intention of "updating" a variable clear to anyone reading the code.
# Basic Assignment count = 10 print(f"Initial count: {count}") # Addition Assignment count += 5 # Equivalent to count = count + 5 print(f"After += 5: {count}") # Subtraction Assignment count -= 2 # Equivalent to count = count - 2 print(f"After -= 2: {count}") # Multiplication Assignment count *= 2 # Equivalent to count = count * 2 print(f"After *= 2: {count}") # Division Assignment count /= 4 # Equivalent to count = count / 4 print(f"After /= 4: {count}") # Modulus Assignment val = 10 val %= 3 # Equivalent to val = val % 3 print(f"Remainder of 10/3: {val}") # Exponent Assignment power = 2 power **= 3 # Equivalent to power = power ** 3 print(f"2 to the power of 3: {power}")
Introduced in Python 3.8, the Walrus Operator (:=) allows you to assign a value to a variable as part of an expression. This is advanced but very useful in loops or conditional checks.
# Example: Assigning and checking a length in one line if (n := len("Python")) > 5: print(f"The word is long ({n} characters).")
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION