How can I swap two Python values without a temporary variable?
Quick answer
Write a, b = b, a. Python evaluates the values on the right before assigning them to the names on the left, so the names receive each other’s original values. For example, if a is 1 and b is 2, afterward a is 2 and b is 1. Two separate assignments like a = b and then b = a instead overwrite the original value of a. [S1]
The question, the details, the next step.
A practical checklist
Identify the two names whose current values should exchange places.
Put both names on the left side of one assignment, separated by a comma.
Put the same names in reverse order on the right:
a, b = b, a.If unsure, try two distinct starting values and inspect both names afterward.
Avoid two sequential assignments that overwrite an original value.
A few more useful answers
Does `a, b = a, b` swap the values?
No. Each name receives its own current value, so that statement leaves them unchanged.
Does the same swap syntax apply in every programming language?
Not necessarily. This describes Python’s assignment behavior; check the rules for another language separately.
Why does tuple unpacking avoid losing either original value?
Python evaluates the right-hand values before assigning them to the left-hand targets, so both original values are available for the assignment. [S1]
Sources
References used for this guide.
- [S1] Python Language Reference: Assignment statements and unpacking docs.python.org · Checked
