Skip to main content

3.0 Python: Assign Multiple Values

3.1 Many Values to Multiple Variables​

Python allows you to assign values to multiple variables in one line:

3.1.1 Example​

x, y, z = "Orange", "Banana", "Cherry"
print(X)
print(y)
print(z)
note

Make sure the number of variables matches the number of values, or else you will get an error.


3.2 One Value to Multiple Variables​

And you can assign the same value to multiple variables in one line:

3.2.1 Example​

x = y = z = "Orange"
print(x)
print(y)
print(z)

3.3 Unpack a Collection​

If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables.
This is called unpacking.

3.3.1 Example​

Unpack a list:

fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)