4.2 Assign Multiple Values

By | September 29, 2021

Many Values to Multiple Variables

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

Example

x, y, z = “Orange”, “Banana”, “Cherry”
print(x)
print(y)
print(z)

Output:

Orange
Banana
Cherry

Unpack a Collection

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

Example

Unpack a list:

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

Output:

apple
banana
cherry

Leave a Reply

Your email address will not be published. Required fields are marked *