Augmented Assignment Operators in Python with Examples
Unlike normal assignment operator, Augmented Assignment Operators are used to replace those statements where binary operator takes two operands says var1
and var2
and then assigns a final result back to one of operands i.e. var1
or var2
.
For example: statement var1 = var1 + 5
is same as writing var1 += 5
in python and this is known as augmented assignment operator. Such type of operators are known as augmented because their functionality is extended or augmented to two operations at the same time i.e. we're adding as well as assigning.
List Of Augmented Assignment Operators in Python
Python has following list of augmented assignment operators:
- Addition & Assignment (
+=
):x+=y
is equivalent tox=x+y
PROGRAM
# Addition a = 23 b = 3 a += b print('Addition = %d' %(a))
OUTPUT
Addition = 26
- Subtraction & Assignment (
-=
):x-=y
is equivalent tox=x-y
PROGRAM
# Subtraction a = 23 b = 3 a -= b print('Subtraction = %d' %(a))
OUTPUT
Subtraction = 20
- Multiplication & Assignment (
*=
):x*=y
is equivalent tox=x*y
PROGRAM
# Multiplication a = 23 b = 3 a *= b print('Multiplication = %d' %(a))
OUTPUT
Multiplication = 69
- Division & Assignment (
/=
):x/=y
is equivalent tox=x/y
PROGRAM
# Division a = 23 b = 3 a /= b print('Division = %f' %(a))
OUTPUT
Division = 7.666667
- Remainder (or Modulo) & Assignment (
%=
):x%=y
is equivalent tox=x%y
PROGRAM
# Remainder or Modulo a = 23 b = 3 a %= b print('Remainder or Modulo = %d' %(a))
OUTPUT
Remainder or Modulo = 2
- Power & Assignment (
**=
):x**=y
is equivalent tox=x**y
PROGRAM
# Power a = 23 b = 3 a **= b print('Power = %d' %(a))
OUTPUT
Power = 12167
- Integer Division & Assignment (
//=
):x//=y
is equivalent tox=x//y
PROGRAM
# Integer Division a = 23 b = 3 a //= b print('Integer Division = %d' %(a))
OUTPUT
Integer Division = 7
- Bitwise Shift Right & Assignment (
>>=
):x>>=y
is equivalent tox=x>>y
PROGRAM
# Bitwise Shift Right a = 23 b = 3 a >>= b print('Bitwise Shift Right = %d' %(a))
OUTPUT
Bitwise Shift Right = 2
- Bitwise Shift Left & Assignment (
>>=
):x<<=y
is equivalent tox=x<<y
PROGRAM
# Bitwise Shift Left a = 23 b = 3 a <<= b print('Bitwise Shift Left = %d' %(a))
OUTPUT
Bitwise Shift Left = 184
- Bitwise AND & Assignment (
&=
):x&=y
is equivalent tox=x&y
PROGRAM
# Bitwise AND a = 23 b = 3 a &= b print('Bitwise AND = %d' %(a))
OUTPUT
Bitwise AND = 3
- Bitwise OR & Assignment (
|=
):x|=y
is equivalent tox=x|y
PROGRAM
# Bitwise OR a = 23 b = 3 a |= b print('Bitwise OR = %d' %(a))
OUTPUT
Bitwise OR = 23
- Bitwise Exclusive OR & Assignment (
^=
):x^=y
is equivalent tox=x^y
PROGRAM
# Bitwise EXCLUSIVE OR a = 23 b = 3 a ^= b print('Bitwise EXCLUSIVE OR = %d' %(a))
OUTPUT
Bitwise EXCLUSIVE OR = 20