Concepts / Variable Assignment and Binding

Variable Assignment and Binding

Swapping two variable values is a fundamental programming operation.

  • 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 Two-Value Exchange

Swapping two variable values is a fundamental programming operation. You may need to exchange two numbers while sorting, switch player positions, or reorder data. Python supports a concise form of tuple assignment that performs the exchange in one statement: a, b = b, a.

python

Before the final statement, a is 5 and b is 10. After it executes, a is 10 and b is 5. The important question is not only what the final values are, but how Python prevents the original value of a from being lost.

Reading Before Rebinding

What do you think happens?

Suppose a is 5 and b is 10. What are the values after a, b = b, a?

  • a is 5 and b is 10

  • a is 10 and b is 5

  • a is 10 and b is 10

Reveal answer
Answer:

a is 10 and b is 5

Python evaluates the right side first. It reads b as 10 and a as 5, then assigns those already-evaluated values to a and b in positional order.

b10a5(10, 5)evaluated valuesa10b5readreadposition 0position 1
What values are read and stored before either variable is changed in the statement a, b = b, a?

The statement has two phases. First, Python evaluates every expression on the right side. For a, b = b, a, it looks up b and a using their current values, producing the ordered values 10 and 5. Only after that evaluation does Python assign the values to the names on the left.

Packing and Unpacking Positions

10tuple position 0areceives position 05tuple position 1breceives position 1assignassign
How are the two right-side values grouped and then matched positionally with the two left-side variables?

The right side supplies two ordered values. In the swap example, the values are grouped as (10, 5). The left side contains two variable names in the order a, b. Python matches the first right-side value with a and the second right-side value with b. This grouping and positional matching are the tuple assignment mechanism behind the swap.

a5a10b10b5value movesvalue moves
How do the original values move to their new variables without one assignment destroying a value needed by the other?

The Complete State Change

a = 5, b = 10initial bindingsa, b = b, aevaluate then assigna = 10, b = 5final bindingsexecuteproduce
How does a, b = b, a change the bindings of a and b from the initial state to the final state?
Worked example

Swapping Two Positions

Two variables represent two player positions. Exchange their values without using a separate temporary variable.

  1. 1
    Initial bindings

    Let left_position be 1 and right_position be 2.

  2. 2
    Evaluate the right side

    The right side reads right_position first and left_position second, producing the ordered values 2 and 1.

  3. 3
    Assign by position

    The first value is assigned to left_position, and the second value is assigned to right_position.

Result

left_position is 2 and right_position is 1.

python

This pattern is useful whenever two existing values need to exchange places. It can appear in sorting algorithms, data rearrangement, and situations where two positions or roles must be exchanged.

Avoiding the Overwrite Trap

  • Common mistake

    Treating the statement as two unrelated assignments that run from left to right

    What it looks like

    a, b = b, a does not first assign b to a and then look up a again for b.

    Why it fails

    Python evaluates all right-side expressions before making the left-side assignments.

    Do this instead

    Trace the right side first: read b, read a, form the ordered values, and then assign them to a and b.

  • Common mistake

    Assuming the first assignment destroys the original value needed by the second assignment

    What it looks like

    If a receives b's value, it may seem that a's original value has disappeared before b can receive it.

    Why it fails

    The original values have already been evaluated and preserved in the ordered right-side result.

    Do this instead

    Separate the operation into its two phases: complete right-side evaluation, followed by left-side assignment.

  • Common mistake

    Replacing the recognized swap pattern with unnecessary temporary-variable steps

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

    This longer form works conceptually, but it takes more steps to read than Python's tuple assignment.

    Do this instead

    Use a, b = b, a when the goal is simply to exchange two values.

ApproachMain stepsReadability in Python
Tuple assignmentEvaluate the right side, then assign by positionConcise and immediately recognizable as a swap
Temporary variableStore one value, move the other value, then restore the stored valueLonger and requires more steps to parse

Both approaches can express an exchange, but tuple assignment communicates the swap directly.

Apply the Two-Phase Trace

EASY

Trace this exchange on paper. Start with first = 12 and second = 20. After first, second = second, first, what value is bound to each variable? Explain the right-side values before describing the assignments.

Hints
  • Read second and first before changing either variable.
  • Place the first evaluated value into first and the second evaluated value into second.
MEDIUM

Explain why a sequential approach that overwrites a before preserving its original value can lose information, then describe how tuple assignment avoids that problem.

Hints
  • Identify which original value could be destroyed first.
  • Use the two phases: evaluate all right-side expressions, then assign to the left-side names.

Essential Takeaways

  1. 1
    The statement a, b = b, a swaps the values bound to a and b in one line.
  2. 2
    Python evaluates every right-side expression before performing the left-side assignments.
  3. 3
    The evaluated values are matched positionally with the left-side variable names.
  4. 4
    Because the original values are preserved before assignment, one variable does not overwrite a value needed by the other.
  5. 5
    Tuple assignment is a concise and readable alternative to a multi-step temporary-variable swap.

At a glance

  • Tuple assignment provides a one-statement way to swap two variable values.
  • Right-side expressions are evaluated completely before left-side assignments occur.
  • The ordered evaluated values prevent the overwriting problem associated with sequential assignment.
  • The pattern is useful in sorting, data rearrangement, and exchanges of positions or roles.

Related concepts

More concepts starting with V