Assignment Operators in Python

What are Assignment Operators?

Assignment operators are used to assign values to variables. In Python, in addition to the simple = assignment, we have compound operators that perform an operation and assign the result to the same variable.

Types of Assignment Operators

Operator Description Example
= Assigns value from right side to left side x = 5
+= Adds right side to left side and assigns result x += 3
(x = x + 3)
-= Subtracts right side from left side x -= 2
(x = x - 2)
*= Multiplies and assigns result x *= 4
(x = x * 4)
/= Divides and assigns result x /= 2
(x = x / 2)
%= Modulus and assigns result x %= 3
(x = x % 3)
//= Floor division and assigns result x //= 2
**= Exponentiation and assigns result x **= 3
(x = x ** 3)
&= Bitwise AND and assigns result x &= 2
|= Bitwise OR and assigns result x |= 3
^= Bitwise XOR and assigns result x ^= 1
>>= Bitwise right shift and assigns result x >>= 1
<<= Bitwise left shift and assigns result x <<= 2

Examples

x = 10
x += 5     # x becomes 15
x *= 2     # x becomes 30
x //= 4    # x becomes 7
x **= 2    # x becomes 49
print(x)   # Output: 49