Sub topic 7
Multiple Assignment and Swapping Values
This chapter assumes you know basic Python variables, how to index a list, and what a tuple is (an ordered, immutable sequence). It also assumes you have seen the idea of packing and unpacking from the previous chapter. Here you will look at how Python runs an assignment with several names, why swapping needs no temporary variable, and where the order of evaluation can surprise you.
Assigning several names in one statement
A statement with several targets on the left and several values on the right is called multiple assignment.
width, height = 1920, 1080
name, age, active = "Ada", 36, True
print(width, height)
print(name, age, active)The right side, 1920, 1080, is a tuple built from the commas. The left side, width, height, is a target list. Python pairs the two up by position. This is ordinary unpacking, so the right side can be any iterable with the correct length, not only a tuple.
r, g, b = [255, 128, 0]
first, second = "hi"
print(r, g, b)
print(first, second)You can also give several names the same starting value, but that is a different feature, covered under chained assignment below.
Swapping without a temporary variable
In many languages, swapping two variables takes three steps and a helper name.
x = 3
y = 4
temp = x
x = y
y = temp
print(x, y)In Python you write one statement.
x = 3
y = 4
x, y = y, x
print(x, y)Both versions print 4 3. The one-line form is shorter and also harder to get wrong, because there is no helper to forget or misuse.
Why it works: the right side is evaluated first
Python runs an assignment in two phases:
- It evaluates the whole right side, left to right, and keeps the resulting objects.
- It binds those objects to the targets, left to right.
By the time any name on the left is rebound, the old values of x and y are already held safely. That is why the swap does not lose a value.
The tempting "sequential" version fails because each line sees the result of the previous one.
a, b = 1, 2
a = b
b = a
print(a, b)This prints 2 2. After a = b, the original value of a is gone, so b = a copies the new value back. Multiple assignment avoids this because all the reads happen before any of the writes.
Is a tuple actually built?
Conceptually the right side is a tuple. In practice, CPython usually optimizes swaps of two or three simple names so that it rearranges values on its stack and does not allocate a tuple. You can check this with the dis module, but you should not rely on it. Write the clear form and let the interpreter optimize it.
Swapping items inside containers
The targets do not have to be plain names. Any assignable target works, including list items, dictionary entries and attributes.
nums = [10, 20, 30, 40]
nums[0], nums[-1] = nums[-1], nums[0]
print(nums)
scores = {"left": 5, "right": 9}
scores["left"], scores["right"] = scores["right"], scores["left"]
print(scores)This prints [40, 20, 30, 10] and then {'left': 9, 'right': 5}. Swapping list items is the core move in many sorting algorithms. Here is a small bubble sort.
def bubble_sort(items):
items = list(items)
for end in range(len(items) - 1, 0, -1):
for i in range(end):
if items[i] > items[i + 1]:
items[i], items[i + 1] = items[i + 1], items[i]
return items
print(bubble_sort([5, 2, 9, 1]))The output is [1, 2, 5, 9]. The function copies its input with list(items), so the caller's list is not modified.
Updating several values at once
Because the right side is evaluated before anything is assigned, you can update several related values from their old values in one step. The classic example is the Fibonacci sequence.
a, b = 0, 1
for _ in range(8):
print(a, end=" ")
a, b = b, a + b
print()This prints 0 1 1 2 3 5 8 13. On each pass, b and a + b are both computed from the old a and b. The same pattern works for the Euclidean algorithm for the greatest common divisor.
def gcd(m, n):
while n:
m, n = n, m % n
return m
print(gcd(48, 18))The result is 6. Writing it as two separate statements would need a temporary variable, and getting the order wrong would silently give a bad answer.
Gotcha: targets are assigned left to right
The right side is fully evaluated first, but the left side is not. Each target is bound in order, and a later target can depend on an earlier one. This matters when a target is a subscript whose index is itself one of the names being assigned.
a = [0, 0, 0]
i = 0
i, a[i] = 1, 5
print(i, a)
b = [0, 0, 0]
j = 0
b[j], j = 5, 1
print(j, b)The first block prints 1 [0, 5, 0]. Python binds i to 1 first, and then evaluates a[i], which is now a[1], and stores 5 there. The second block prints 1 [5, 0, 0]. Here b[0] is assigned first, while j is still 0.
The same ordering rule explains why repeating a target keeps only the last value.
a, a = 1, 2
print(a)This prints 2. Python does not complain, but code like this is almost always a typo. Linters flag it.
Chained assignment is a different feature
Do not confuse multiple assignment with chained assignment, which gives one value to several names.
x = y = 0
print(x, y)
p = q = []
p.append(1)
print(q)The second block prints [1]. Chained assignment evaluates the right side once and binds the same object to every target, so p and q refer to one list. For immutable values like integers, this is harmless. For mutable values like lists, it is a common bug. If you want separate lists, use multiple assignment with two separate expressions.
p, q = [], []
p.append(1)
print(p, q)This prints [1] [].
| Form | Example | What happens |
|---|---|---|
| Multiple assignment | `a, b = 1, 2` | Two values, paired with two targets by position |
| Chained assignment | `a = b = 1` | One value, bound to both names |
| Swap | `a, b = b, a` | Right side read first, then both names rebound |
| Starred assignment | `a, *rest = items` | Leftover items collected into a list |
Errors to expect
If the number of targets does not match the number of values, Python raises ValueError. The message tells you which way the mismatch goes.
try:
a, b = 1, 2, 3
except ValueError as e:
print(e)
try:
a, b, c = 1, 2
except ValueError as e:
print(e)The messages are too many values to unpack (expected 2) and not enough values to unpack (expected 3, got 2). A starred target, covered in a later chapter, is the way to accept a variable number of values.
Augmented assignment does not combine with multiple targets. A line such as a, b += 1, 2 is a SyntaxError, because += needs a single target. Write a += 1 and b += 2 as separate statements.
Finally, remember that swapping rebinds names. It does not copy objects. After x, y = y, x with two lists, x simply refers to the list that y used to refer to. Any other name that referred to those lists is unchanged.
x = [1]
y = [2]
alias = x
x, y = y, x
print(x, y, alias)This prints [2] [1] [1]. The name alias still points to the original first list, which is now y.
When to use it
Use multiple assignment when the values are naturally a pair or group, such as coordinates, loop state, or a swap. Avoid it when the right side is long or each value needs its own explanation. In that case separate lines read better. A statement like a, b, c, d = f(x), g(y), h(z), k(w) forces the reader to match four names to four calls by position.
Exercise
What does this code print, and why? i = 0, nums = [10, 20, 30], then i, nums[i] = 2, 99, then print(i, nums).
Show answer
It prints 2 [10, 20, 99]. The right side 2, 99 is evaluated first. Then the targets are bound left to right. i becomes 2 first, so the second target nums[i] means nums[2], and 99 is stored there. The first element is unchanged.
Exercise
A learner writes a = b = [] and then calls a.append(1). They expected b to stay empty. Why is it not empty, and how would you fix it?
Show answer
Chained assignment evaluates [] once and binds the same list object to both names, so a and b share it and b is also [1]. To get two separate lists, write a, b = [], [] or use two statements, a = [] and b = [].
Exercise
Write one statement that rotates three variables so that a gets the value of b, b gets the value of c, and c gets the old value of a.
Show answer
a, b, c = b, c, a. The right side is evaluated first using the old values, so no value is lost, and then the three names are rebound in order.