Augmented Assignment Operators in Python

Augmented Assignment Operators in Python

In Python, augmented assignment operators are used to perform an operation on a variable and assign the result to that same variable. They provide a shorthand way of rewriting expressions. Here are the augmented assignment operators in Python:

  1. +=: Adds the right operand to the left operand and assigns the result to the left operand.

    x = 5 x += 3 # Equivalent to x = x + 3 print(x) # Outputs: 8 
  2. -=: Subtracts the right operand from the left operand and assigns the result to the left operand.

    x = 5 x -= 3 # Equivalent to x = x - 3 print(x) # Outputs: 2 
  3. *=: Multiplies the left operand by the right operand and assigns the result to the left operand.

    x = 5 x *= 3 # Equivalent to x = x * 3 print(x) # Outputs: 15 
  4. /=: Divides the left operand by the right operand and assigns the result to the left operand.

    x = 5 x /= 2 # Equivalent to x = x / 2 print(x) # Outputs: 2.5 
  5. %=: Takes the modulus of the left operand by the right operand and assigns the result to the left operand.

    x = 5 x %= 3 # Equivalent to x = x % 3 print(x) # Outputs: 2 
  6. //=: Performs floor division on the operands and assigns the result to the left operand.

    x = 5 x //= 2 # Equivalent to x = x // 2 print(x) # Outputs: 2 
  7. **=: Raises the left operand to the power of the right operand and assigns the result to the left operand.

    x = 5 x **= 3 # Equivalent to x = x ** 3 print(x) # Outputs: 125 
  8. &=: Performs a bitwise "AND" operation and assigns the result to the left operand.

    x = 5 # Binary: 101 x &= 3 # Binary: 011 print(x) # Outputs: 1 (Binary: 001) 
  9. |=: Performs a bitwise "OR" operation and assigns the result to the left operand.

    x = 5 # Binary: 101 x |= 3 # Binary: 011 print(x) # Outputs: 7 (Binary: 111) 
  10. ^=: Performs a bitwise "XOR" operation and assigns the result to the left operand.

    x = 5 # Binary: 101 x ^= 3 # Binary: 011 print(x) # Outputs: 6 (Binary: 110) 
  11. <<=: Left shifts the bits of the left operand and assigns the result to the left operand.

    x = 5 # Binary: 101 x <<= 1 # Left shift by 1 print(x) # Outputs: 10 (Binary: 1010) 
  12. >>=: Right shifts the bits of the left operand and assigns the result to the left operand.

    x = 5 # Binary: 101 x >>= 1 # Right shift by 1 print(x) # Outputs: 2 (Binary: 10) 

These operators are commonly used to shorten operations where a variable is operated upon and then assigned the result.


More Tags

process primeng-datatable lookup-tables ntlm palindrome batch-processing manager-app admin store nstextview

More Programming Guides

Other Guides

More Programming Examples