Swap Two Numbers in Python
What you'll learn
- What swapping means and why ordering matters.
- Classic temp-variable swap and Python tuple swap.
- XOR swap for integers and its caveats.
Overview
Swap means exchanging values between two variables without losing either value.
Prerequisites
Basic variables, assignment, and print() in Python.
What does swapping do?
If a=5 and b=10, after swap a=10 and b=5.
Live preview
Algorithm
1
Save first value
temp = a
2
Move second to first
a = b
3
Restore saved value
b = temp
📜 Pseudocode
Pseudocode
temp = a
a = b
b = temp1
Swap using temp variable
python
num1 = 5
num2 = 10
print(f"Before swapping: num1 = {num1}, num2 = {num2}")
temp = num1
num1 = num2
num2 = temp
print(f"After swapping: num1 = {num1}, num2 = {num2}")2
Swap using tuple unpacking (Python way)
python
num1 = 5
num2 = 10
print(f"Before swapping: num1 = {num1}, num2 = {num2}")
num1, num2 = num2, num1
print(f"After swapping: num1 = {num1}, num2 = {num2}")3
Swap without temp variable (XOR trick)
python
a = 5
b = 10
if a != b:
a ^= b
b ^= a
a ^= b
print(f"After swapping: a = {a}, b = {b}")Notes
Preferred style: In Python, a, b = b, a is cleanest and safest.
XOR swap: Mainly interview trick for integers.
❓ FAQ
After swapping, the first variable stores the old value of the second, and the second stores the old value of the first.
Not always. Python supports tuple unpacking: a, b = b, a.
It teaches the core memory idea and works similarly across many languages.
Yes for integers, but it is less readable than tuple swap, so it's mostly an interview trick.
Swap still works; values remain the same.
🔄 Input / output examples
| Before | After |
|---|---|
| 5, 10 | 10, 5 |
| 0, 3 | 3, 0 |
| -4, 20 | 20, -4 |
| 7, 7 | 7, 7 |
Edge cases
Same values
No visible change
Swap is still correct.
XOR caveat
Use only for integers
Tuple swap is preferred in Python.
⏱️ Time and space complexity
| Version | Time | Extra space |
|---|---|---|
| Temp swap | O(1) | O(1) |
| Tuple swap | O(1) | O(1) |
| XOR swap | O(1) | O(1) |
Summary
- Core idea: exchange values without losing either one.
- Python-preferred:
a, b = b, a. - All swap variants are constant-time.
Did you know?
Swapping values is one of the smallest building blocks in sorting. In Python, a, b = b, a is the most readable way for everyday code.
8 people found this page helpful
