PythonMastery

Assign several variables at once in Python

Give several variables the same value with x = y = z = 0, or different values in one line with a, b, c = 1, 2, 3.

Python lets you assign more than one variable in a single line. There are two different forms.

The program

python
x = y = z = 100
a, b, c = 1, 2, 3

print(x, y, z)
print(a, b, c)
output
100 100 100
1 2 3

How it works

When the counts don't match

python
try:
    a, b = 1, 2, 3
except ValueError as error:
    print(error)
output
too many values to unpack (expected 2)

The ValueError: too many values to unpack page explains this error in detail.

Learn the idea: Variables & Data Types