Skip to content

Assignment operators in Python

  • by

Python Assignment Operators are used to assign values to variables. The assignment operator is represented as the “=” symbol used in assignment statements and assignment expressions.

Following are the different types of assignment operators in Python:

OperatorDescriptionSyntax
=Assign the value of the right side of the expression to the left side operandx = y + z 
+=Add and Assign: Add right side operand with left side operand and then assign to left operanda += b   
-=Subtract AND: Subtract the right operand from the left operand and then assign it to the left operand: True if both operands are equala -= b  
*=Multiply AND: Multiply the right operand with the left operand and then assign it to the left operanda *= b     
/=Divide AND: Divide left operand with right operand and then assign to left operanda /= b
%=Modulus AND: Takes modulus using left and right operands and assigns result to left operanda %= b  
//=Divide(floor) AND: Divide the left operand with the right operand and then assign the value(floor) to the left operanda //= b   
**=Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operanda **= b     
&=Performs Bitwise AND on operands and assigns value to left operanda &= b   
|=Performs Bitwise OR on operands and assigns value to left operanda |= b    
^=Performs Bitwise xOR on operands and assigns value to left operanda ^= b    
>>=Performs Bitwise right shift on operands and assigns value to left operanda >>= b     
<<=Performs Bitwise left shift on operands and assigns value to left operanda <<= b 

The right-hand side value or operand is assigned to the left-hand operand.

Assignment operators in Python

Simple example code.

a = 5  # assign value
b = a  # assign the expression to the left operand

print("b value = ", b)

# a = a + b assign the expression to the left operand
a +=b
print("a + b = ", a)

# a = a - b or a -= b assign the expression to the left operand
a -= b
print("a - b = ", a)

# a = a * b, or a *= b assign the expression to the left operand
a *= b
print("a * b = ", a)

# a = a / b or a /= b assign the expression to the left operand
a /= b
print("a / b = ", a)

# a = a % b or a %= b assign the expression to the left operand
a %= b
print("a % b = ", a)

Output:

Assignment operators in Python

Complete code list

OperatorExampleEquivalent to
=x = 5x = 5
+=x += 5x = x + 5
-=x -= 5x = x – 5
*=x *= 5x = x * 5
/=x /= 5x = x / 5
%=x %= 5x = x % 5
//=x //= 5x = x // 5
**=x **= 5x = x ** 5
&=x &= 5x = x & 5
|=x |= 5x = x | 5
^=x ^= 5x = x ^ 5
>>=x >>= 5x = x >> 5
<<=x <<= 5x = x << 5

Do comment if you have any doubts or suggestions on this Python operator topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *