Multiple assignment
- Python course
- Beginner
- Lesson 8/116
- 4 min
Learn multiple assignment with a, b = 1, 2.
Multiple assignment
Python can assign values to several variables in one line. This is called multiple assignment:
a, b, c = 1, 2, 3The right side is a tuple, the left side is a list of names. Python matches each variable in order: a=1, b=2, c=3.
This is shorter than assigning each variable on its own line. But to keep code readable, avoid more than 3-4 variables on one line.
Tuple unpacking
Under multiple assignment lies tuple unpacking. The values on the right first form a tuple, then the left side unpacks it.
point = (10, 20)
x, y = pointHere point is a tuple; x, y = point splits it into two variables. The number of variables must match the tuple length, or Python raises an error.
Practice Print with multiple assignment
Do a multiple assignment with x, y = 10, 20. Then print their sum with print(x + y).
Starter code
# Do the multiple assignmentSample solution
x, y = 10, 20
print(x + y)Expected output
30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Assign to a and b
a, b ____ 1, 2
a, b = 1, 2
Explanation: a, b = 1, 2 is a multiple assignment.
2 After a, b, c = 1, 2, 3 what is b?
- 2 Correct answer
- 1
- 3
- It raises an error
Explanation: b takes the second value: 2.
3 Match the concepts
| Term | Meaning |
|---|---|
= |
Assignment |
a, b = 1, 2 |
Multiple assignment |
type(x) |
Learn the type |
age = 25 |
Single variable assignment |