Python Assign Multiple Values

Python lets you assign several variables at once, which keeps related setup concise and readable.

Many variables in one line

You can assign values to multiple variables on a single line by separating both the names and the values with commas. Python pairs them up by position: the first value goes to the first name, the second value to the second name, and so on. This is often called tuple unpacking.

Assigning several variables at once

x, y, z = 1, 2, 3

print(x)   # 1
print(y)   # 2
print(z)   # 3
Note: The number of names on the left must match the number of values on the right. A mismatch raises a ValueError such as 'not enough values to unpack'.

One value for many variables

When you want several variables to start from the same value, you can chain the assignments. Every name to the left of the value ends up referring to that single value.

Sharing one value

a = b = c = 0

print(a, b, c)   # 0 0 0

Unpacking a collection

Unpacking also works when the values come from a list, tuple, or other sequence. This is a clean way to pull items out of a collection into individually named variables.

Unpacking a list

colors = ["red", "green", "blue"]
primary, secondary, tertiary = colors

print(secondary)   # green
  • Comma-separated assignment pairs values to names by position.
  • Chained assignment (a = b = c = value) gives every name the same value.
  • You can unpack any sequence whose length matches the number of names.
  • A starred name, such as first, *rest = numbers, collects the remaining items into a list.

Swapping without a temporary variable

left = "A"
right = "B"

left, right = right, left
print(left, right)   # B A