Multiple Assignment

Concepts covered: Unpacking

Python has a convenient feature that lets you assign values to multiple variables in a single line. This makes certain patterns cleaner and more readable.

Assigning Multiple Vars

x, y, z = 1, 2, 3
name, age, city = "Maya", 28, "Austin"

print(x, y, z)
print(name, age, city)

Output:

1 2 3
Maya 28 Austin

The values on the right are matched up with the variables on the left, in order.

Swapping Values

In many languages, swapping requires a temporary variable. In Python:

a = 10
b = 20
print("Before:", a, b)

a, b = b, a
print("After:", a, b)

Output:

Before: 10 20
After: 20 10

Python evaluates the right side first (b, a), then assigns to the left side. No temp variable needed.

Unpacking from Collections

You can "unpack" a tuple into separate variables:

coordinates = (10, 20)
x, y = coordinates
print(x, y)

quotient, remainder = divmod(17, 5)
print(quotient, remainder)

Output:

10 20
3 2

Now x is 10 and y is 20. divmod(17, 5) returns (3, 2), so quotient is 3 and remainder is 2.

Pythonic
  • a, b = b, a
  • x, y = get_coordinates()
  • quotient, rem = divmod(17, 5)
Verbose
  • temp = a; a = b; b = temp
  • result = get_coordinates(); x = result[0]; y = result[1]
  • result = divmod(17, 5); quotient = result[0]; rem = result[1]

The simultaneous evaluation is what makes multiple assignment safe. Python builds the right-hand tuple first, then unpacks it, so no value is overwritten before it is read.

Unpacking from functions like divmod() or enumerate() follows the same principle. Any iterable on the right side can be unpacked into any matching number of variables on the left.

About this lesson

This section is part of the Python Expressions: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.