Concepts / Iterables and Iteration

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.

  • Programming
Interactive lab

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

  1. 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.
  2. For each assignment, evaluate the complete right side first, looking every name up in the variable table as it is now.
  3. 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).
  4. 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.
  5. 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.
  6. 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.

Educational simulation

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.

python

What do you think happens?

After the assignment, which value is bound to each variable?

  • x contains 'have' and y contains 'fun'

  • x contains 'fun' and y contains 'have'

  • Both variables contain the complete tuple

Reveal answer
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.

mtuple'have'position 0x'have''fun'position 1y'fun'containscontainsposition 0position 1
How does each value in a tuple move into the variable at the corresponding position?
Key point

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.

python

What do you think happens?

After a, b = b, a executes, what values do a and b contain?

  • a contains 'first' and b contains 'second'

  • a contains 'second' and b contains 'first'

  • Both variables contain 'first'

Reveal answer
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.

a'first'a'second'b'second'b'first'after assignmentafter assignment
How do the values of two variables change before and after a tuple-assignment swap?

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.

a, b = b, aright side valuesold b, old aswapped a and btemporary-variableswaptemporary variableswapped a and bevaluate firstunpackstore a valuecomplete swap
What steps and temporary storage differ between tuple assignment and traditional temporary-variable swapping?
Best practice

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.

python
Output
ValueError: too many values to unpack
1, 2, 3three valuesValueErrorcount mismatcha, btwo variablesunpackdoes not match
What happens when the number of variables does not match the number of values being unpacked?
  • Common mistake

    Providing more values than variables

    What it looks like
    a, b = (1, 2, 3)
    Why it fails

    There are three values but only two destinations, so the third value has no variable to receive it.

    Do this instead

    Make the number of variables match the number of values before running the assignment.

  • Common mistake

    Providing fewer values than variables

    What it looks like
    a, b, c = (1, 2)
    Why it fails

    The exact-count rule is not satisfied; one variable would have no corresponding value.

    Do this instead

    Check both sides of the assignment and ensure their counts are equal.

Practice the Binding Order

EASY

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.
Worked example

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.

  1. 1
    Count the destinations

    The left side provides two variables.

  2. 2
    Count the values

    The right side provides three values.

  3. 3
    Compare the counts

    The counts differ, so the assignment cannot give every value a destination.

Result

Change the assignment so that the number of variables exactly matches the number of values.

Key Takeaways

  1. 1
    Tuple assignment unpacks values by position into separate variables.
  2. 2
    The number of variables must exactly match the number of values being unpacked.
  3. 3
    The idiom a, b = b, a swaps two values without a separately named temporary variable.
  4. 4
    Python evaluates the complete right-hand side before binding the left-hand variables.
  5. 5
    A mismatched unpacking count raises ValueError and 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.
  • ValueError during unpacking usually indicates a mismatch between the number of variables and values.

Related concepts

More concepts starting with I