Lesson 5 of 5 · Variables · 2 min read · Updated
Multiple Assignment
Python can assign several variables in a single line, which makes swapping values easy.
Several Variables at Once
Put the names on the left of the = and the values on the right, separated by commas. The counts must match. You can also give the same value to several names by chaining the = sign.
name, age, city = "Priya", 22, "Madurai"
print(name, age, city)
x = y = z = 0
print(x, y, z)
Priya 22 Madurai
0 0 0
Swapping Two Values
first = "idli"
second = "dosa"
first, second = second, first
print(first)
print(second)
dosa
idli
Example
Python evaluates the whole right side before assigning anything, so both old values are safely in hand when the swap happens. In many other languages this needs a third temporary variable.
Warning
The number of names must equal the number of values. Writing a, b = 1, 2, 3 raises a ValueError about too many values to unpack.
Create a free account to save your progress, or sign in.