🎓 A1Learner
🔍

Python Assign Multiple Values

Multiple assignment stores several values in several variables in one line. Commas match each value to a name in order.

One value at a time

Each name needs its own line here.

x = 1
y = 2
z = 3
print(x)
print(y)
print(z)

Many values, many names

Each name gets the value in its place.

x, y, z = 1, 2, 3
print(x)
print(y)
print(z)

One value, many names

All three names share the same value.

a = b = c = 0
print(a)
print(b)
print(c)

Swap two values

One line swaps the two values.

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

Example

first_score = 40
second_score = 75
print("Before:", first_score, second_score)
first_score, second_score = second_score, first_score
print("After:", first_score, second_score)

Key points

  • Use commas to match each value to a name in order
  • Give one value for each name in a many-value line
  • Use a = b = value to give one value to many names
  • Packing: grouping values together before sharing them out
  • Use a, b = b, a to swap two values in one line
  • One line can store several values in several variables at once.

In this example, first_score starts at 40. The second score starts at 75. The first print shows the before state. The swap line packs both values, then shares them back swapped. The last print shows the after state.

Note

The swap needs no extra temporary variable.

Python packs the right side first, then unpacks it.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

You run a = 3, then b = 8, then a, b = b, a. What does print(a) show?