Concepts / Understanding Python's Assignment Model

Understanding Python's Assignment Model

Tuple unpacking (a, b = b, a) is the fastest and most Pythonic way to swap two variables

  • Programming

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.

read current valuespreserve orderunpack and assigna, b5, 10b, a10, 5Temporary tuple10, 5a, b10, 5
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.

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

Exchanging Two Scores

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

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

Preserve both values: Python preserves the pair 10 and 5 before changing either left-side name.

Assign by position: The first preserved value goes to a, and the second preserved value goes to b.

a represents 10 and b represents 5.

value movesvalue movesa5a10b10b5
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
Python preserves valuesstore explicitlycontinue assignmentsa, b = b, aone statementRead aexplicit stepTemporary tuplehandled internallytempexplicit storageAssign valuesseveral statements
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

  • Using sequential assignment without preserving the original value

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

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

  • Forgetting the comma syntax

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

    Fix: Write both names and both right-side values with comma separators: a, b = b, a.

  • Accidentally rotating more than two variables

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

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

  • Providing a different number of values on the two sides

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

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

tuple unpackinga = b; b = athree-position assignmentunequal value counta, b5, 10a, b10, 5a, b10, 10a, b, cb, c, aValue count2 names, 1 value
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. Python swaps two values with the concise statement a, b = b, a.
  2. Python evaluates the complete right side before assigning to the left side.
  3. The internally preserved values prevent the original values from being lost.
  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. Tuple unpacking is more concise, readable, and efficient than explicitly writing a temporary-variable swap.

Key Takeaways

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