This article explains several simple and idiomatic ways to write a Python program that swaps the values of two variables. Each method includes code, a short explanation, and notes so you can choose the best approach for your situation.
Given two variables a and b, exchange their values so that after the operation a holds the original value of b and b holds the original value of a.
Example:
# before
a = 5
b = 10
# after swap
# a == 10, b == 5
Code language: PHP (php)
This is a clear, language-agnostic method that works everywhere.
# Using a temporary variable
a = 5
b = 10
print("Before swap:", a, b)
temp = a
a = b
b = temp
print("After swap:", a, b)
Code language: PHP (php)
Output:

Explanation:
a into temp so its value is not lost.b to a.temp into b.Python supports multiple assignment (tuple unpacking), which makes swapping concise and readable.
# Tuple unpacking
a = 5
b = 10
print("Before swap:", a, b)
a, b = b, a
print("After swap:", a, b)
Code language: PHP (php)
Output :

Explanation:
The right-hand side (b, a) creates a temporary tuple of values and Python unpacks it into a and b. This performs the swap in one readable statement.
You can swap numeric values using arithmetic operations. This avoids an extra variable but is less readable and has caveats.
# Using addition and subtraction
a = 5
b = 10
print("Before swap:", a, b)
# Correct in-place arithmetic swap
a = a + b
b = a - b
a = a - b
print("After swap:", a, b)
Code language: PHP (php)
Important caveats:
Another classic trick uses bitwise XOR. It works only for integers and is rarely used in Python because tuple unpacking is clearer.
# XOR swap — integer-only
a = 5
b = 10
print("Before swap:", a, b)
a = a ^ b
b = a ^ b
a = a ^ b
print("After swap:", a, b)
Code language: PHP (php)
Caveats:
You can wrap swapping logic in a function; this is useful for clarity when reusing the pattern.
def swap(x, y):
return y, x
# usage
a, b = 1, 2
print("Before:", a, b)
a, b = swap(a, b)
print("After:", a, b)
Code language: PHP (php)
This uses tuple returns and unpacking under the hood.
All methods shown run in O(1) time (constant time) and use O(1) extra space. Tuple unpacking conceptually creates a small temporary tuple (constant-size), but in practice this cost is negligible for two values.