Iterables and Iteration
Read tuple assignment from right to left as a positional transfer: values are produced on the right, then matched with destinations on the left. The ordering on both sides matters.
Try it: Assignment, Statement by Statement
How an assignment statement evaluates its right side first (using the names' current values) and only then binds the name on the left: updating x = x + 1, augmented operators like += and //=, chained a = b = 0, simultaneous a, b = b, a + b versus one-at-a-time assignment, rebinding a name to a value of another type, the NameError for a name that was never assigned, and the SyntaxError for a name that breaks the naming rules.
How it works
- Before anything runs, Python compiles the whole program; a name that breaks the rules (starts with a digit, contains a space or a dash, or is a keyword) is a SyntaxError and no line runs at all.
- For each assignment, evaluate the complete right side first, looking every name up in the variable table as it is now.
- Then bind the name(s) on the left to that value: a new name is added to the table, an existing one is replaced (even by a value of a different type).
- x += 5 reads x, applies the operator (+, -, *, //, %, **) and binds the result back to x; a = b = 0 evaluates 0 once and binds a, then b.
- a, b = b, a + b builds the whole right-hand tuple from the OLD values before binding a and b; two separate statements would use the new a in the second line.
- Reading a name that is not in the table raises NameError and the program stops at that line.
Default run (10 steps): A 4-line program. Python first compiles all of it, then runs it top to bottom. The variable table on the right starts empty. … Program finished. Final table: x = 16.
Simplified: The programs are fixed templates: you choose the template, its numbers, the operator and the variable name, never the code. The lab's own small Python tokenizer and parser (written for the statements these programs use: assignments, print calls, if / elif / else, for, while, def and return) checks the text; nothing is executed as real Python. Every program the lab can show was compiled by CPython 3.12 and the lab reproduces its exception type, message, line, caret columns and the printed report. A small interpreter written for the same statements then runs them (integers of any size, the str/float results these templates produce, and print); each program was also run in CPython 3.12 under sys.settrace, and the lab reproduces the variables after every line, the output and the error.
Loading the simulation…
A Tuple with Two Destinations
Tuple assignment lets one statement unpack multiple values from a tuple into separate variables. The central rule is positional: the first value goes to the first variable, the second value goes to the second variable, and so on. For unpacking to succeed, the number of variables and values must match exactly.
What do you think happens?
After the assignment, which value is bound to each variable?
Reveal answer
x contains 'have' and y contains 'fun'
Python matches positions. The value at tuple position 0, 'have', is assigned to x, and the value at position 1, 'fun', is assigned to y.
Position-by-Position Unpacking
In the statement x, y = m, the left side provides two variable destinations and the right side provides the two values from m. Python pairs them by position. The first tuple element is assigned to x, while the second tuple element is assigned to y. Both bindings occur together as one assignment operation rather than as two separately written assignments.
Read tuple assignment from right to left as a positional transfer: values are produced on the right, then matched with destinations on the left. The ordering on both sides matters.
Swapping Without a Temporary Variable
Tuple assignment is especially useful for swapping two variables. The Pythonic idiom is a, b = b, a. It exchanges the values without requiring a separately named temporary variable.
What do you think happens?
After a, b = b, a executes, what values do a and b contain?
Reveal answer
a contains 'second' and b contains 'first'
Python evaluates the complete right side first. It obtains the current value of b followed by the current value of a, then assigns those two values to a and b in that order.
The Right Side Runs First
The swap is safe because Python evaluates the entire right-hand side before binding anything on the left. In a, b = b, a, Python first obtains the old value of b and the old value of a in that order. It then unpacks those values into a and b. Because the right side is completed before the left side changes, one original value cannot be overwritten before it is used.
Prefer tuple assignment for a two-variable swap. The source describes it as more readable, faster, and more idiomatic than traditional approaches that use a temporary variable.
When Counts Do Not Match
Unpacking requires an exact count match. If three values are supplied but only two variables are available, Python has nowhere to assign the third value and raises a ValueError. The same principle applies whenever the number of variables and values differs.
ValueError: too many values to unpackCommon mistake Providing more values than variables
What it looks likea, b = (1, 2, 3)Why it failsThere are three values but only two destinations, so the third value has no variable to receive it.
Do this insteadMake the number of variables match the number of values before running the assignment.
Common mistake Providing fewer values than variables
What it looks likea, b, c = (1, 2)Why it failsThe exact-count rule is not satisfied; one variable would have no corresponding value.
Do this insteadCheck both sides of the assignment and ensure their counts are equal.
Practice the Binding Order
Suppose a tuple contains the values 10 and 20. Write a tuple-assignment statement that places 10 in first_value and 20 in second_value. Then write a second statement that swaps the values of those two variables using tuple assignment.
Hints
- Place the variable names on the left and the tuple values on the right.
- For the swap, put the variables in reverse order on the right side.
- Check that both assignments have the same number of destinations and values.
Diagnosing an Unpacking Error
An assignment has two variables on the left and three values on the right. Explain why it raises ValueError and describe the required correction.
- 1Count the destinations
The left side provides two variables.
- 2Count the values
The right side provides three values.
- 3Compare the counts
The counts differ, so the assignment cannot give every value a destination.
Change the assignment so that the number of variables exactly matches the number of values.
Key Takeaways
- 1Tuple assignment unpacks values by position into separate variables.
- 2The number of variables must exactly match the number of values being unpacked.
- 3The idiom a, b = b, a swaps two values without a separately named temporary variable.
- 4Python evaluates the complete right-hand side before binding the left-hand variables.
- 5A mismatched unpacking count raises
ValueErrorand should be debugged by counting both sides.
At a glance
- Tuple assignment maps values to variables according to their positions.
- Successful unpacking requires equal counts on both sides.
- Tuple assignment makes variable swapping concise and avoids a named temporary variable.
- Python evaluates the right side first, protecting the original values during a swap.
ValueErrorduring unpacking usually indicates a mismatch between the number of variables and values.