Assignment Operators in Python
Assignment operators are used to assign values to variables.
They also include augmented assignment operators, which combine an operation with assignment in one step.
1. = Simple Assignment Assigns the value from the right-hand side to the left-hand variable (creates a binding between a name and an object).
Example:
Python
# Simple assignment x = 10 # x now refers to integer 10 # Multiple assignment a, b = 1, 2 # a=1, b=2 # Chained assignment (all refer to same object) m = n = 100 # both m and n point to 100
2. += Addition Assignment Adds the right-hand operand to the left-hand operand and assigns the result to the left operand.
Python
x = 5 x += 3 # same as x = x + 3 print(x) # 8
Works on numbers, strings, lists.
Example: not Operator.
Python
s = "Hi" s += " Ashish" # string concatenation print(s) # "Hi Ashish" lst = [1, 2] lst += [3, 4] # list extends in-place print(lst) # [1, 2, 3, 4]
3. -= Subtraction Assignment It subtracts right operand from the left operand and assigns the result to left operand.
Python
x = 10 x -= 4 # x = x - 4 print(x) # 6
4. *= Multiplication Assignment It multiplies right operand with the left operand and assigns the result to left operand.
Python
x = 7 x *= 3 # x = x * 3 print(x) # 21 # Works with strings (repetition) msg = "Hi " msg *= 3 print(msg) # "Hi Hi Hi "