Lesson 03
Assignment Operator
Assign values with =, multi-target assignment, swap without a temp variable, and short-hand operators like += and *=.
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.
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:
variable = value
variable = expressionOne RHS value goes into one LHS variable.
a = 10
b = 20
c = a + b
print(a, b, c)10 20 302. Multi-target assignment
Assign multiple variables in a single statement.
Syntax:
var1, var2 = value1, value2a, b = 10, 20
c, d, e = a + b, a - b, a * b
print(c, d, e)30 -10 200Another example:
sno, sname, marks = 10, "Rossum", 34.561. 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.
a, b = 10, 20
print(a, b)
a, b = b, a
print(a, b)10 20
20 104. Short-hand assignment operators
Instead of:
n = n + 5You can write:
n += 5Common 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 |
x = 10 # assignment
x == 10 # comparison → TruePractice exercises
Exercise 1 — Assign three student details on one line:
sno, name, marks = 101, "Alice", 95.5Exercise 2 — Swap two strings:
city1, city2 = "Hyderabad", "Delhi"
city1, city2 = city2, city1Exercise 3 — Rewrite using short-hand:
n = n * 2Answer: n *= 2
Quick knowledge check
-
What does
=do?
It assigns the RHS value or expression to the LHS variable. -
What does
a, b = b, ado?
It swaps the values ofaandb. -
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, aswaps 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…