Many Values to Multiple Variables
A single line of Python can give values to several variables at once.
Note: You need exactly one value per variable here. If the counts differ, Python raises an error.
Example
Prompt
Assign "Orange", "Banana", and "Cherry" to three variables x, y, z in one line, then print each.
Output: complete Python program
main.py
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
One Value to Multiple Variables
One line is also enough to give several variables the same value:
Example
Prompt
Assign the same value "Orange" to three variables x, y, z in one line, then print each.
Output: complete Python program
main.py
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpack a Collection
When your values are already in a collection, such as a list or a tuple, Python can pull them out into separate variables. We call this unpacking.
Unpack a list
Prompt
Create a list of fruits ["apple", "banana", "cherry"], unpack it into three variables x, y, z, and print each.
Output: complete Python program
main.py
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)