Concepts / Understanding Python's Assignment Model

Understanding Python's Assignment Model

Python provides a shorter assignment pattern: a, b = b, a.

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

The Swap Problem

Swapping two variables means exchanging the values currently associated with their names. This is useful when sorting numbers, exchanging player scores, or reordering data in a collection. In many programming languages, the usual solution requires a temporary holding variable so that the first value is not lost. Python provides a shorter assignment pattern: a, b = b, a.

What do you think happens?

Suppose a refers to 5 and b refers to 10. What values will a and b have after a, b = b, a?

  • a is 5 and b is 10

  • a is 10 and b is 5

  • Both a and b are 10

Reveal answer
Answer:

a is 10 and b is 5

The right side is evaluated as the current values of b and a, in that order. Those values are then assigned to a and b on the left.

The Two-Phase Assignment

Python safely performs the swap in two phases. First, it evaluates the entire right side, b, a, using the current values of the variables. Python internally preserves those values in a temporary tuple. Second, it unpacks the preserved values and assigns them to the names on the left, a and b. Because both original values are captured before either name is reassigned, neither value is lost.

a, b5, 10b, a10, 5Temporary tuple10, 5a, b10, 5read current valuespreserve orderunpack and assign
What happens first, and how does Python preserve both original values during a, b = b, a?

Mapping Values to Names

python

The positions determine the swap. The first value on the right, the current value of b, is assigned to the first name on the left, a. The second value on the right, the current value of a, is assigned to the second name on the left, b. The comma syntax creates the multiple-value structure that Python unpacks.

b10a10a5b5position 1position 2
How does each value on the right map to its new variable on the left?
Worked example

Exchanging Two Scores

Let a represent 5 and b represent 10. Apply a, b = b, a.

  1. 1
    Read the right side

    The right side supplies the current values of b and a, which are 10 and 5.

  2. 2
    Preserve both values

    Python preserves the pair 10 and 5 before changing either left-side name.

  3. 3
    Assign by position

    The first preserved value goes to a, and the second preserved value goes to b.

Result

a represents 10 and b represents 5.

a5a10b10b5value movesvalue moves
What do a and b refer to before and after executing a, b = b, a?

Why This Pattern Is Preferred

ApproachExplicit stepsIntermediate storageClarity
Tuple unpackingOne assignment statementHandled internally by PythonConcise and immediately recognizable as a swap
Temporary variableSeveral assignmentsAn explicitly named temporary variableCorrect but more verbose

Both approaches exchange two values, but tuple unpacking expresses the operation more directly.

a, b = b, aone statementRead aexplicit stepTemporary tuplehandled internallytempexplicit storageAssign valuesseveral statementsPython preserves valuesstore explicitlycontinue assignments
How do the steps and intermediate storage differ between tuple unpacking and a temporary-variable swap?

Tuple unpacking is more concise, readable, and efficient than the traditional temporary-variable approach. The source describes it as faster because Python's interpreter optimizes this common pattern. The practical benefit is also communicative: a, b = b, a immediately signals to another programmer that the operation is a swap.

Mistakes That Lose Values

  • Common mistake

    Using sequential assignment without preserving the original value

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

    After the first assignment, a has b's original value. The original value of a is no longer available for the second assignment.

    Do this instead

    Use a, b = b, a, which evaluates the right side before assigning either left-side name.

  • Common mistake

    Forgetting the comma syntax

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

    This does not express two corresponding positions for tuple unpacking and does not perform the intended exchange.

    Do this instead

    Write both names and both right-side values with comma separators: 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

    The values are assigned according to all three positions, so this performs a three-variable rotation rather than a two-variable swap.

    Do this instead

    For a two-variable swap, include exactly the two intended names and their two corresponding right-side values.

  • Common mistake

    Providing a different number of values on the two sides

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

    The left side names two positions, while the right side provides one value, so the assignment cannot map one value to each name.

    Do this instead

    Ensure that the number of unpacked values matches the number of target names.

a, b5, 10a, b10, 5a, b10, 10a, b, cb, c, aValue count2 names, 1 valuetuple unpackinga = b; b = athree-position assignmentunequal value count
What goes wrong when the assignment order, variable names, or number of values is incorrect?

Practice the Pattern

EASY

Suppose a represents 12 and b represents 3. Write the single Python assignment statement that exchanges their values. Then state the value represented by each name after the assignment.

Hints
  • Put the two target names on the left, separated by a comma.
  • Put the values in reverse name order on the right.
  • The right side is evaluated before either left-side name changes.
MEDIUM

A learner writes a = b; b = a to swap two values. Explain why the result is incorrect and rewrite the operation using tuple unpacking.

Hints
  • Track the value of a immediately after the first assignment.
  • Ask whether the original value of a is still available for the second assignment.
  • Use the two-phase evaluation behavior of a, b = b, a.

The Essential Takeaways

  1. 1
    Python swaps two values with the concise statement a, b = b, a.
  2. 2
    Python evaluates the complete right side before assigning to the left side.
  3. 3
    The internally preserved values prevent the original values from being lost.
  4. 4
    The comma positions map the first right-side value to the first left-side name and the second right-side value to the second left-side name.
  5. 5
    Tuple unpacking is more concise, readable, and efficient than explicitly writing a temporary-variable swap.

At a glance

  • Tuple unpacking lets Python exchange two variable values in one statement.
  • The right side is evaluated first, preserving both original values before assignment occurs.
  • In a, b = b, a, the right-side values map to the left-side names by position.
  • Sequential assignment can overwrite a value, while missing commas or mismatched value counts prevent the intended unpacking.
  • The tuple-unpacking form is concise, readable, efficient, and recognizable as the Python swap idiom.

Related concepts

More concepts starting with U