Temp Variable
Classic
Save, overwrite, restore.
Swapping exchanges two variables so each holds the other’s old value: a=5, b=10 becomes a=10, b=5. You will use a temp variable, Python’s a, b = b, a, and an optional XOR trick for integers — plus a live preview and worked examples.
Classic
Save, overwrite, restore.
a, b = b, a
The Pythonic everyday swap.
Integers
Interview curiosity, not style.
Order
Save before you overwrite.
Try 5 & 10
Swap custom integers instantly.
All variants
Constant time and space.
Swapping means exchanging the values of two variables without losing either one. If you write a = b first, the old a is gone forever — that is why beginners learn a temporary holder.
In Python you can skip the explicit temp with tuple unpacking: a, b = b, a. Interviews still like the classic three-step swap because it transfers to C, Java, and sorting algorithms.
Swap is a building block for sorting, partitioning, and many in-place algorithms.
temp holds a copy.
a, b = b, a
Integers only.
7, 7 stays 7, 7.
In short: exchange values without losing either — prefer a, b = b, a in Python.
Given two variables, exchange their values so each holds what the other used to hold.
# Before: a = 5, b = 10
# After: a = 10, b = 5 | Item | Type | Description |
|---|---|---|
a, b | any / int | Values to exchange (XOR needs ints). |
| Result | same types | a holds old b; b holds old a. |
temp | same as a | Optional holding spot. |
temp = a
a = b
b = temp | Method | Idea | Notes |
|---|---|---|
| Temp variable | Save, overwrite, restore | Universal across languages |
| Tuple unpacking | a, b = b, a | Preferred in Python |
| XOR | a ^= b; b ^= a; a ^= b | Integers; interview trick |
| Goal | Pattern |
|---|---|
| Temp save | temp = a |
| Overwrite | a = b |
| Restore | b = temp |
| Pythonic | a, b = b, a |
| XOR (ints) | a ^= b; b ^= a; a ^= b |
| Equal values | Swap still correct; no visible change |
Same result — different packaging.
temp = aClearest cross-language idea
a, b = b, aEveryday Python style
a ^= bIntegers only; less readable
a = b firstLoses the old a
Reach for a swap whenever two values need to trade places in place.
First assignment / memory drill.
Bubble / selection / partition swaps.
arr[i], arr[j] = arr[j], arr[i]
Temp swap proves shared concepts.
Stick to temp or tuple then.
Key benefit: one tiny idea — save before overwrite — that shows up in almost every in-place algorithm.
Enter two integers and swap them with a temporary variable.
Three complete Python programs — temp variable, tuple unpacking, and XOR for integers. Click View Output to reveal sample console results.
The classic three-step swap that works in almost every language.
Save the first value, overwrite it, then restore into the second variable.
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}") temp keeps 5 while num1 becomes 10. Then num2 receives the saved 5.
Tuple unpacking does the same exchange in one line.
Preferred everyday style in Python. The right-hand side builds a temporary pair first.
num1 = 5
num2 = 10
print(f"Before swapping: num1 = {num1}, num2 = {num2}")
num1, num2 = num2, num1
print(f"After swapping: num1 = {num1}, num2 = {num2}") Python evaluates (num2, num1) first, then unpacks into num1 and num2. No explicit temp name is needed.
Works for integers. Prefer tuple unpacking in real Python code; keep XOR as an interview curiosity.
a = 5
b = 10
if a != b:
a ^= b
b ^= a
a ^= b
print(f"After swapping: a = {a}, b = {b}") Three XOR steps rearrange the bit patterns so a and b trade places. The a != b guard avoids a known edge when both aliases point at the same location in some languages; for plain Python ints it is still a good habit to mention.
Save the first value.
Copy the second into the first.
Restore the saved value into b.
Neither original was lost.
Follow the temp variable through each assignment.
| Step | a | b | temp |
|---|---|---|---|
| start | 5 | 10 | — |
| temp = a | 5 | 10 | 5 |
| a = b | 10 | 10 | 5 |
| b = temp | 10 | 5 | 5 |
If you assign a = b first without saving, the original 5 disappears.
Where swaps show up beyond the interview prompt.
Assignment and memory basics.
Example: temp swap of 5, 10.
Bubble and selection swaps.
Example: adjacent pairs.
arr[i], arr[j] = arr[j], arr[i]
Example: in-place reorder.
Quicksort-style exchanges.
Example: pivot swaps.
Why overwrite order matters.
Example: walkthrough table.
Continue the interview chain.
Example: related CTA.
Pro Tip: say “save before overwrite” before you write the three lines.
Why learning all three approaches is useful.
Same idea in C, Java, JS, and more.
One line, hard to get wrong in Python.
O(1) time and space for all variants.
Useful trivia once you know the readable form.
Pro Tip: lead with temp or tuple; mention XOR only if asked about “without a temp”.
Small habits that keep swap solutions interview-ready.
Never a = b as the first step alone.
a, b = b, a for production code.
Makes demos and debugging clearer.
Integers only; mention readability cost.
7, 7 should remain 7, 7.
Pro Tip: sanity-check (5, 10), (7, 7), and (-4, 20) — if those three work, you are solid.
Mistakes that commonly break swap programs.
Writing a = b without saving a.
→ Use temp or tuple unpacking.
Floats and strings do not XOR.
→ Use temp or tuple instead.
Missing one of the three ^= steps.
→ Prefer a, b = b, a in Python.
Expecting failure when a == b.
→ Swap is still correct.
Clever but harder to maintain.
→ Use the readable form.
Handle these before claiming the swap is complete.
Swap is still correct.
Tuple swap is preferred in Python.
-4 and 20 swap fine.
0, 3 becomes 3, 0.
Skip XOR.
arr[i], arr[j] = arr[j], arr[i]
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
a, b = b, a.Quick Takeaway: save before overwrite — or write a, b = b, a.
| Version | Time | Extra space |
|---|---|---|
| Temp swap | O(1) | O(1) |
| Tuple swap | O(1) | O(1) |
| XOR swap | O(1) | O(1) |
Swapping two variables does a fixed number of assignments regardless of the values.
Swapping exchanges two values without losing either one. Learn the temp-variable pattern for every language, prefer a, b = b, a in Python, and treat XOR as optional trivia.
Practice the three examples above, then continue to triangular numbers.
Save first — or use a, b = b, a.
Exchange values safely — then use the idea in sorting.
save / set / restore
Classica, b = b, a
Pythonints only
Trickstill correct
EdgeO(1)
AnalysisSwapping values is one of the smallest building blocks in sorting. In Python, a, b = b, a is the most readable way for everyday code.
Learn how to check whether a number is triangular in Python.
8 people found this page helpful