Swap Two Numbers in Python

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Basics

What You’ll Learn

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.

Temp Variable

Classic

Save, overwrite, restore.

Tuple Unpacking

a, b = b, a

The Pythonic everyday swap.

XOR Trick

Integers

Interview curiosity, not style.

No Data Loss

Order

Save before you overwrite.

Live Preview

Try 5 & 10

Swap custom integers instantly.

O(1)

All variants

Constant time and space.

Introduction

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.

Why it matters?

Swap is a building block for sorting, partitioning, and many in-place algorithms.

Key Highlights

Save First

temp holds a copy.

Pythonic

a, b = b, a

XOR Caveat

Integers only.

Equal OK

7, 7 stays 7, 7.

In short: exchange values without losing either — prefer a, b = b, a in Python.

📝 Problem & Approach

Given two variables, exchange their values so each holds what the other used to hold.

python
# Before: a = 5,  b = 10
# After:  a = 10, b = 5

Inputs & Outputs

ItemTypeDescription
a, bany / intValues to exchange (XOR needs ints).
Resultsame typesa holds old b; b holds old a.
tempsame as aOptional holding spot.

Minimal workflow

Pseudocode
temp = a
a = b
b = temp

Method comparison

MethodIdeaNotes
Temp variableSave, overwrite, restoreUniversal across languages
Tuple unpackinga, b = b, aPreferred in Python
XORa ^= b; b ^= a; a ^= bIntegers; interview trick

⚡ Quick Reference

GoalPattern
Temp savetemp = a
Overwritea = b
Restoreb = temp
Pythonica, b = b, a
XOR (ints)a ^= b; b ^= a; a ^= b
Equal valuesSwap still correct; no visible change

📋 Temp vs Tuple vs XOR

Same result — different packaging.

Temp
temp = a

Clearest cross-language idea

Tuple
a, b = b, a

Everyday Python style

XOR
a ^= b

Integers only; less readable

Wrong
a = b first

Loses the old a

Context

When This Problem Shows Up

Reach for a swap whenever two values need to trade places in place.

  1. Interview basics

    First assignment / memory drill.

  2. Sorting steps

    Bubble / selection / partition swaps.

  3. List elements

    arr[i], arr[j] = arr[j], arr[i]

  4. Cross-language interviews

    Temp swap proves shared concepts.

  5. Not for XOR on floats

    Stick to temp or tuple then.

Key benefit: one tiny idea — save before overwrite — that shows up in almost every in-place algorithm.

🔮 Live Preview

Enter two integers and swap them with a temporary variable.

Two integers in JavaScript safe integer range.

Live result
Press “Swap”.

Examples Gallery

Three complete Python programs — temp variable, tuple unpacking, and XOR for integers. Click View Output to reveal sample console results.

📚 Getting Started

The classic three-step swap that works in almost every language.

Example 1 — Swap Using Temp Variable

Save the first value, overwrite it, then restore into the second 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}")

How It Works

temp keeps 5 while num1 becomes 10. Then num2 receives the saved 5.

⚡ The Python Way

Tuple unpacking does the same exchange in one line.

Example 2 — Swap Using Tuple Unpacking

Preferred everyday style in Python. The right-hand side builds a temporary pair first.

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}")

How It Works

Python evaluates (num2, num1) first, then unpacks into num1 and num2. No explicit temp name is needed.

Example 3 — Swap Without Temp (XOR Trick)

Works for integers. Prefer tuple unpacking in real Python code; keep XOR as an interview curiosity.

python
a = 5
b = 10

if a != b:
    a ^= b
    b ^= a
    a ^= b

print(f"After swapping: a = {a}, b = {b}")

How It Works

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.

🧠 How the Temp Swap Works

1

temp = a

Save the first value.

Hold
2

a = b

Copy the second into the first.

Overwrite
3

b = temp

Restore the saved value into b.

Restore
=

Values exchanged

Neither original was lost.

🔎 Worked Walkthrough — 5 and 10

Follow the temp variable through each assignment.

Stepabtemp
start510
temp = a5105
a = b10105
b = temp1055

If you assign a = b first without saving, the original 5 disappears.

Use Cases

Where swaps show up beyond the interview prompt.

1. Interview Warm-ups

Assignment and memory basics.

Example: temp swap of 5, 10.

2. Sorting Algorithms

Bubble and selection swaps.

Example: adjacent pairs.

3. List Elements

arr[i], arr[j] = arr[j], arr[i]

Example: in-place reorder.

4. Partition Steps

Quicksort-style exchanges.

Example: pivot swaps.

5. Teaching Memory

Why overwrite order matters.

Example: walkthrough table.

6. Next: Triangular

Continue the interview chain.

Example: related CTA.

Pro Tip: say “save before overwrite” before you write the three lines.

Advantages

Why learning all three approaches is useful.

  1. 1. Temp Is Portable

    Same idea in C, Java, JS, and more.

  2. 2. Tuple Is Readable

    One line, hard to get wrong in Python.

  3. 3. Constant Cost

    O(1) time and space for all variants.

  4. 4. XOR Shows Bit Tricks

    Useful trivia once you know the readable form.

Pro Tip: lead with temp or tuple; mention XOR only if asked about “without a temp”.

Usage Tips

Small habits that keep swap solutions interview-ready.

  1. 1. Save Before Overwrite

    Never a = b as the first step alone.

  2. 2. Prefer Tuple in Python

    a, b = b, a for production code.

  3. 3. Print Before and After

    Makes demos and debugging clearer.

  4. 4. Keep XOR Optional

    Integers only; mention readability cost.

  5. 5. Test Equals

    7, 7 should remain 7, 7.

Pro Tip: sanity-check (5, 10), (7, 7), and (-4, 20) — if those three work, you are solid.

Common Pitfalls

Mistakes that commonly break swap programs.

  1. 1. Overwriting Too Soon

    Writing a = b without saving a.

    → Use temp or tuple unpacking.

  2. 2. XOR on Non-Integers

    Floats and strings do not XOR.

    → Use temp or tuple instead.

  3. 3. Incomplete XOR Chain

    Missing one of the three ^= steps.

    → Prefer a, b = b, a in Python.

  4. 4. Thinking Equals Is Broken

    Expecting failure when a == b.

    → Swap is still correct.

  5. 5. Forcing XOR in Production

    Clever but harder to maintain.

    → Use the readable form.

Edge Cases

Handle these before claiming the swap is complete.

Same values

No visible change

Swap is still correct.

XOR caveat

Integers only

Tuple swap is preferred in Python.

Negatives

Temp / tuple OK

-4 and 20 swap fine.

Zeros

Valid

0, 3 becomes 3, 0.

Strings / floats

Use temp or tuple

Skip XOR.

List indices

Same pattern

arr[i], arr[j] = arr[j], arr[i]

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Sorting building block. Almost every in-place sort swaps elements.
  • Tuple evaluates RHS first. That is why a, b = b, a is safe.
  • XOR is optional trivia. Prefer readability unless asked specifically.
  • All variants are O(1). Cost does not grow with the numbers’ magnitude.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Temp swap 5, 10

  • Reproduce Example 1
  • Expect 10, 5

2. Tuple swap

  • Use a, b = b, a
  • Same result

3. Equal values

  • Swap 7, 7
  • Confirm still 7, 7

4. List indices

  • Swap arr[0] and arr[1]
  • Use unpacking

Notes

  • Core idea: exchange values without losing either one.
  • Python-preferred: a, b = b, a.
  • XOR: mainly an interview trick for integers.
  • All swap variants are constant-time and constant extra space.

Quick Takeaway: save before overwrite — or write a, b = b, a.

⏱️ Time and Space Complexity

VersionTimeExtra space
Temp swapO(1)O(1)
Tuple swapO(1)O(1)
XOR swapO(1)O(1)

Swapping two variables does a fixed number of assignments regardless of the values.

Wrap Up

🎉 Conclusion

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.

💡 Best Practices

✅ Do

  • Save before overwrite
  • Prefer a, b = b, a in Python
  • Print before and after
  • Know the temp pattern
  • Test equal values

❌ Don’t

  • Assign a = b first alone
  • XOR floats or strings
  • Skip readability for cleverness
  • Assume equals breaks swap
  • Forget list-index unpacking exists

Key Takeaways

Knowledge Unlocked

Five things to remember about swapping

Exchange values safely — then use the idea in sorting.

5
Core concepts
, 02

Tuple

a, b = b, a

Python
^ 03

XOR

ints only

Trick
= 04

Equals

still correct

Edge
O 05

Cost

O(1)

Analysis

❓ Frequently Asked Questions

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.
Yes. Temp and tuple swap work for any values; XOR is for integers only.
All common swap variants are O(1) time and O(1) extra space.
Show temp first, then mention a, b = b, a as the Pythonic way.

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.

Continue to Triangular Number

Learn how to check whether a number is triangular in Python.

Triangular number tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful