Lesson 10 +10 XP

Assign Multiple Values

Assign Multiple Values

Python can assign many values in one line, which other languages often can't.

Many values to many variables

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

The number of variables must match the number of values.

One value to many variables

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

All three point to the same value.

Unpacking a collection

A list or tuple can be unpacked into variables:

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

This works because the list has exactly three items.

A handy swap trick

Python makes swapping two variables trivial:

a = 1
b = 2
a, b = b, a
print(a)  # 2
print(b)  # 1

No temp variable needed.

TL;DR

  • x, y, z = 1, 2, 3 assigns many at once.
  • x = y = z = 1 shares one value.
  • A list or tuple can be unpacked into variables.
  • Swapping is just a, b = b, a.