Assigning to multiple variables at the same time in Python

You can easily assign values to more than one variable simultaneously in Python.

The number of variables on the left side of the assignment must match the number of values on the right side.

a, b = 4, 'Tokyo'

print(a)
print(b)
4
Tokyo

Otherwise you will get an error when trying to unpack the values:

>>> a, b = 4, 'Tokyo', 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)

The way to solve this is to use the *args syntax as shown in Functions in Python.

So the first value ‘bmw’ goes to brand, and the other values will be packed in a list that we called brand_list, notice the * in brand_list when assigning, after the assignment, you can use brand_list without the * normally.

brand, *brand_list = 'bmw', 'ferrari', 'toyota', 'suzuki'

print(f'brand -> {brand}')
print(f'brand_list -> {brand_list}')
brand -> bmw
brand_list -> ['ferrari', 'toyota', 'suzuki']

Watch on Youtube

You can also watch this content on Youtube: