Concepts / Multiple Assignment and Simultaneous Binding

Multiple Assignment and Simultaneous Binding

A careless sequential assignment can lose one of the original values, but Python provides a single statement that performs the exchange safely.

  • 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…

Why Swapping Needs Care

Swapping means exchanging the values held by two variables. This is useful when sorting numbers, exchanging player scores, or reordering data. A careless sequential assignment can lose one of the original values, but Python provides a single statement that performs the exchange safely.

What do you think happens?

Suppose a is 10 and b is 20. What will a and b contain after a, b = b, a?

  • a is 10 and b is 20

  • a is 20 and b is 10

  • Both variables contain 20

  • Both variables contain 10

Reveal answer
Answer:

a is 20 and b is 10

Python first captures the current values of b and a in that order, then assigns those captured values to a and b.

The Two-Phase Assignment

The expression a, b = b, a works because Python handles it in two phases. First, Python evaluates the complete right side and creates a temporary tuple containing the current value of b followed by the current value of a. Second, Python unpacks those two values and binds them to a and b on the left side. Because both original values are captured before either variable is reassigned, neither value is lost.

a10Temporary tuple(20, 10)a20b20b10first valuesecond valueunpackunpack
How does Python capture the original values of b and a before assigning them to a and b?
Code walkthrough
a = 10
b = 20
a, b = b, a
  1. 1
    Python reads the right side first, so it captures 20 and 10 before changing either variable.
  2. 2
    Python assigns the first captured value, 20, to a.
  3. 3
    Python assigns the second captured value, 10, to b.
  • The variables begin with different values.
  • The right side is evaluated as the current value of b followed by the current value of a.
  • The captured values are unpacked into a and b.
Output
After the swap, a is 20 and b is 10.

A Complete Swap Trace

Worked example

Exchange Two Scores

Exchange the values of player_one_score and player_two_score without writing an explicit temporary variable.

  1. 1
    Starting values

    player_one_score is 45 and player_two_score is 60.

  2. 2
    Write the values in reverse order

    Place player_two_score first and player_one_score second on the right side: player_one_score, player_two_score = player_two_score, player_one_score.

  3. 3
    Evaluate the right side

    Python captures the current values as 60 and 45 before assigning either result.

  4. 4
    Unpack to the left side

    The first captured value goes to player_one_score, and the second goes to player_two_score.

Result

player_one_score is 60 and player_two_score is 45.

a10a20b20b10swapswap
What are the values of a and b before and after executing a, b = b, a?

Why the Idiom Is Preferred

Tuple unpackingTemporary-variable method
a, b = b, aUses several explicit assignment steps
No explicitly written temporary variableRequires a temporary holding variable to preserve an original value
Concise and readableMore verbose
Python optimizes this common pattern and executes it more efficientlyThe source describes tuple unpacking as less efficient than this pattern

Both approaches can exchange two values, but tuple unpacking is the preferred Python idiom according to the source material.

a, b10, 20Tuple(20, 10)a, b20, 10a, b10, 20Temporary variable10a, b20, 10evaluateunpackpreserve acomplete steps
How does data move through tuple unpacking compared with the step-by-step temporary-variable method?

Mistakes That Break a Swap

  • Common mistake

    Using sequential assignment without preserving the first value

    What it looks like
    a = b; b = a
    Why it fails

    After the first assignment, a contains the original value of b. The original value of a has been lost, so the second assignment cannot recover it.

    Do this instead

    Use a, b = b, a so Python captures both original values before either variable is reassigned.

  • Common mistake

    Forgetting the comma syntax

    What it looks like
    a = b, a
    Why it fails

    The left side no longer names two variables for unpacking, so the statement does not express the intended two-variable swap.

    Do this instead

    Write two targets separated by a comma: a, b = b, a.

  • Common mistake

    Writing the right-side values in the wrong order

    What it looks like
    a, b = a, b
    Why it fails

    The values are assigned in their original order, so this does not exchange them.

    Do this instead
    Reverse the right-side order: a, b = b, a.
  • Common mistake

    Accidentally rotating more than two variables

    What it looks like
    a, b, c = b, c, a
    Why it fails

    This statement moves three values according to a three-variable order rather than performing a simple two-variable swap.

    Do this instead

    For a two-variable swap, use exactly two targets and place their names in reverse order on the right side.

atargetbfirst value,separates targets,separates valuesbtargetasecond valuefirst to firstsecond to second
What happens when the number of values does not match the number of variables, or when the assignment order is written incorrectly?

Practice the Binding Order

EASY

Write a Python statement that swaps the values of first_item and second_item. Then explain which original value is evaluated first on the right side and where it is assigned on the left side.

Hints
  • Use two names on the left side separated by a comma.
  • Place the names in reverse order on the right side.
  • The first value evaluated on the right side is the current value of second_item.
MEDIUM

Debug this attempted swap: a = 3; b = 8; a = b; b = a. Identify the original value that is lost and rewrite the code using simultaneous binding.

Hints
  • Trace the values immediately after the first assignment.
  • The original value of a must be captured before a changes.
  • The corrected form places b first on the right side and a second.

The Pythonic Pattern

  1. 1
    For a two-variable swap, write a, b = b, a. Python evaluates the complete right side first, preserving both original values in an internal temporary tuple. It then unpacks those values into the left-side variables. This approach is concise, readable, and described in the source as faster and more efficient than the traditional temporary-variable method. When debugging, check the comma syntax, the order of the names, and whether a sequential assignment has accidentally overwritten an original value.

Key Takeaways

  • Tuple unpacking swaps two values with the syntax a, b = b, a.
  • Python evaluates the right side completely before assigning to the left side.
  • The current value of b becomes the new value of a, and the current value of a becomes the new value of b.
  • The tuple-unpacking pattern is concise, readable, and described as more efficient than the traditional temporary-variable approach.
  • Common errors include sequential assignment without a temporary value, missing comma syntax, incorrect order, and accidentally rotating more than two variables.

Related concepts

More concepts starting with M