Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 03

Assignment Operator

Assign values with =, multi-target assignment, swap without a temp variable, and short-hand operators like += and *=.

Beginner15 min

The assignment operator (=) transfers the right-hand side (RHS) value or expression into the left-hand side (LHS) variable.

Python uses assignment in two main ways: single assignment and multi-target assignment.

RHS expression stored in LHS variable

What you'll learn

  • Single assignment (=)
  • Multi-target assignment on one line
  • Swapping variables without a temporary variable
  • Short-hand assignment operators (+=, -=, *=, …)

1. Single-line assignment

Syntax:

text
variable = value
variable = expression

One RHS value goes into one LHS variable.

python
a = 10
b = 20
c = a + b

print(a, b, c)
text
10 20 30

2. Multi-target assignment

Assign multiple variables in a single statement.

Syntax:

python
var1, var2 = value1, value2
python
a, b = 10, 20
c, d, e = a + b, a - b, a * b

print(c, d, e)
text
30 -10 200

Another example:

python
sno, sname, marks = 10, "Rossum", 34.56

1. Single-line assignment

c = a + b

c = 30

2. Multi-target assignment

a, b = 10, 20

  • c = a + b → 30
  • d = a - b → -10
  • e = a * b → 200

c, d, e = a+b, a-b, a*b → 30, -10, 200

3. Swapping variables

After swap: a = "Alice", b = "Bob"

4. Short-hand assignment

n = 10

3. Swapping variables

Python can swap two variables without a temporary variable.

python
a, b = 10, 20
print(a, b)

a, b = b, a
print(a, b)
text
10 20
20 10

4. Short-hand assignment operators

Instead of:

python
n = n + 5

You can write:

python
n += 5

Common short-hand operators:

Operator Equivalent
+= n = n + value
-= n = n - value
*= n = n * value
/= n = n / value
//= n = n // value
%= n = n % value
**= n = n ** value

Assignment vs equality

Operator Purpose
= Assign a value to a variable
== Compare two values
python
x = 10      # assignment
x == 10     # comparison → True

Practice exercises

Exercise 1 — Assign three student details on one line:

python
sno, name, marks = 101, "Alice", 95.5

Exercise 2 — Swap two strings:

python
city1, city2 = "Hyderabad", "Delhi"
city1, city2 = city2, city1

Exercise 3 — Rewrite using short-hand:

python
n = n * 2

Answer: n *= 2

Quick knowledge check

  1. What does = do?
    It assigns the RHS value or expression to the LHS variable.

  2. What does a, b = b, a do?
    It swaps the values of a and b.

  3. Is == an assignment operator?
    No. == is the equality comparison operator.

Summary

  • = assigns values; it does not compare.
  • Python supports single and multi-target assignment.
  • a, b = b, a swaps variables without a temporary variable.
  • Short-hand operators like +=, -=, and *= make updates concise.

Next lesson: Relational Operators — compare values and get True or False.

Loading playground…