Assignment Operators

4 min read ·

Assignment operators in Python are used to assign values to variables. They also allow you to update a variable’s value in a shorter and cleaner way.
Assignment operators help reduce code length and improve readability.

What Are Assignment Operators?

Assignment operators assign values to variables or modify existing values.
Here:
  • = is the assignment operator
  • x is the variable
  • 10 is the value

Types of Assignment Operators

OperatorDescription
=Assign
+=Add and assign
-=Subtract and assign
*=Multiply and assign
/=Divide and assign
%=Modulus and assign
//=Floor divide and assign
**=Exponent and assign
&=Bitwise AND and assign
|=Bitwise OR and assign
^=Bitwise XOR and assign
>>=Right shift and assign
<<=Left shift and assign

Basic Assignment (=)

Assigns a value to a variable.

Add and Assign (+=)

Adds a value and assigns the result.

Subtract and Assign (-=)

Subtracts a value and assigns the result.

Multiply and Assign (*=)

Multiplies and assigns the result.

Divide and Assign (/=)

Divides and assigns the result (always float).

Modulus and Assign (%=)

Finds remainder and assigns.

Floor Divide and Assign (//=)

Performs floor division and assigns.

Exponent and Assign (**=)

Raises to power and assigns.

Bitwise Assignment Operators (Advanced)


The Walrus Operator (:=)

The Walrus Operator allows you to assign and use a value in the same expression. It was introduced in Python 3.8.

Why It’s Special

  • Reduces repeated calculations
  • Makes conditions cleaner
  • Often used inside if and while

Basic Walrus Operator Example


Walrus Operator in while Loop (Very Powerful)


Walrus vs Normal Assignment

Without Walrus

With Walrus


When NOT to Use Walrus Operator

  • When it reduces readability
  • In very simple assignments
  • If teammates are beginners
Best Practice

Use the walrus operator only when it improves clarity, not just to be clever.


Practice

  • Use all assignment operators on one variable
  • Rewrite a loop using walrus operator
  • Compare readability with and without walrus
  • Predict output of walrus-based conditions