To swap two numbers means exchange their values: after the swap, the first variable holds what the second had, and the second holds what the first had.
Remember
Before: a = 5, b = 10
After: a = 10, b = 5
Default interview answer:
temp = a
a = b
b = temp
Pythonic everyday code:
a, b = b, a
Method
Idea
Notes
Temp variable
Save, overwrite, restore
Clearest language-agnostic answer
Tuple unpack
a, b = b, a
Most Pythonic
XOR
Three ^= steps
Integers only; interview trick
Approach
How to Swap Two Numbers in Python
Four clear steps for the temp method — then Pythonic and XOR variants.
Store the first value in temp.
Copy the second value into the first variable.
Copy temp into the second variable.
Or use a, b = b, a in real Python code; mention XOR only if asked.
Method
Idea
Time
Best for
Temp variable
temp = a; a = b; b = temp
O(1)
Interviews across languages
Tuple unpack
a, b = b, a
O(1)
Everyday Python
XOR
a ^= b three times
O(1)
Integer bit trick
Pseudocode
Pseudocode
function SwapTemp(a, b):
temp = a
a = b
b = temp
return a, b
function SwapTuple(a, b):
a, b = b, a
return a, b
function SwapXor(a, b):
if a != b:
a = a XOR b
b = b XOR a
a = a XOR b
return a, b
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Interview default
Use a temporary variable
Temp steps
temp = a; a = b; b = temp
Pythonic
a, b = b, a
Equal values
Swap still works; result unchanged
XOR
Integers only — not for floats
Classic check
5, 10 → 10, 5
Try it
Live Preview
Enter two integers and swap them with the temporary-variable method.
Whole numbers only. Tap a chip or type a pair.
Result
Before: a = 5, b = 10
temp = 5
a = 10
b = 5
After: a = 10, b = 5
Trace
Worked Walkthrough — a = 5, b = 10
Trace the temporary-variable swap step by step.
Calculation
Start: a = 5, b = 10
Step 1: temp = a → temp = 5
Step 2: a = b → a = 10
Step 3: b = temp → b = 5
Result: a = 10, b = 5
Code
Python Programs
Start with a temporary variable — the interview default. Then show tuple unpacking and XOR as alternatives.
Example 1 — Swap Using Temp Variable
Save the first value, overwrite it, then restore into the second variable.