Python Assignment Operators
Assignment Operators
Assignment operators are used to assign values to variables.
note
There are various compound operators in Python.
For example, a += 2
adds 2 to the variable and then assigns it to the variable. It is equivalent to a = a + 2
.
Operator | Description | Example | Equivalent to |
---|---|---|---|
= | Assign value of right side of expression to left side operand | x = 2 | x = 2 |
+= | Add right-side operand with left side operand and then assign to left operand | x += 2 | x = x + 2 |
-= | Subtract right operand from left operand and then assign to left operand | x -= 2 | x = x - 2 |
*= | Multiply right operand with left operand and then assign to left operand | x *= 2 | x = x * 2 |
/= | Divide left operand with right operand and then assign to left operand | x /= 2 | x = x / 2 |
%= | Takes modulus using left and right operands and assign the result to left operand | x %= 2 | x = x % 2 |
//= | Divide left operand with right operand and then assign the value(floor) to left operand | x //= 2 | x = x // 2 |
**= | Calculate exponent(raise power) value using operands and assign value to left operand | x **= 2 | x = x ** 2 |
&= | Performs Bitwise AND on operands and assign value to left operand | x &= 2 | x = x & 2 |
&124;= | Performs Bitwise OR on operands and assign value to left operand | x &124;= 2 | x = x &124; 2 |
^= | Performs Bitwise XOR on operands and assign value to left operand | x ^= 2 | x = x ^ 2 |
>>= | Performs Bitwise right shift on operands and assign value to left operand | x >>= 2 | x = x >> 2 |
<<= | Performs Bitwise left shift on operands and assign value to left operand | x <<= 2 | x = x << 2 |
Examples
Assign
a = 2
b = 3
result = a + b
print(result) # 5
Add and Assign
a = 2
b = 3
a += b # a = a + b
print(a) # 5
Subtract and Assign
a = 2
b = 3
a -= b # a = a - b
print(a) # -1
Multiply and Assign
a = 2
b = 3
a *= b # a = a * b
print(a) # 6
Divide and Assign
a = 2
b = 3
a /= b # a = a / b
print(a) # 0.6666666666666666
Modulus and Assign
a = 2
b = 3
a %= b # a = a % b
print(a) # 2
Divide (floor) and Assign
a = 2
b = 3
a //= b # a = a // b
print(a) # 0
Exponent and Assign
a = 2
b = 3
a **= b # a = a ** b
print(a) # 8
Bitwise AND and Assign
a = 2 # 2 (0010)
b = 3 # 3 (0011)
a &= b # a = a & b
print(a) # 2 (0010)
Bitwise OR and Assign
a = 2 # 2 (0010)
b = 3 # 3 (0011)
a |= b # a = a | b
print(a) # 3 (0011)
Bitwise XOR and Assign
a = 2 # 2 (0010)
b = 3 # 3 (0011)
a ^= b # a = a ^ b
print(a) # 1 (0001)
Bitwise Right Shift and Assign
a = 2 # 2 (0010)
b = 3 # 3 (0011)
a >>= b # a = a >> b
print(a) # 0 (0000)
Bitwise Left Shift and Assign
a = 2 # 2 (0010)
b = 3 # 3 (0011)
a <<= b # a = a << b
print(a) # 16 (1000)