To swap two values in Python, use a, b = b, a. Python evaluates the values on the right before unpacking them into the names on the left, so the values exchange places without a temporary variable.
Swap two values with one assignment
a = 10
b = 20
a, b = b, a
print(a) # 20
print(b) # 10
The comma is the key: b, a forms a tuple of the current values, and Python unpacks that pair into a and b. Parentheses are optional, so a, b = b, a is the usual concise idiom. The Python 3.14.8 Language Reference itself gives this assignment as an example of swapping two variables: Simple statements: assignment statements.
Swap values with a temporary variable
a = 10
b = 20
temp = a
a = b
b = temp
This three-step version first saves the original value of a, then replaces a with b, and finally puts the saved value into b. It is useful for understanding the underlying idea of preserving a value before overwriting its name, but it is not required for an ordinary two-variable swap in Python.
Swap values through a function
def swapped(a, b):
return b, a
x = 10
y = 20
x, y = swapped(x, y)
The function returns the two values in reverse order as a pair. The caller must unpack that returned pair—or assign it to another name—to rebind its own variables. Assigning to the function parameters alone does not reassign the caller’s local names; parameter names are local to the function call.
Recommended Free Tools
#1 Best Overall
When swapping indexed items, mind assignment order
For simple names such as a and b, the direct idiom is straightforward. Assignments with overlapping targets, such as an index variable and an item addressed by that variable, are more subtle: Python assigns targets on the left from left to right. For example, in i, x[i] = 1, 2, i is changed before Python evaluates the target x[i], so that item target uses the new index. The language reference describes this left-to-right behavior and warns that overlapping targets can cause confusion: Python Language Reference, assignment statements.
Quick Recap
Best Value
Rank #2
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




