Python Swap Two Numbers Program

Beginner
5 min read
Updated: Oct 2026
3 programs
Live preview

What Does Swap Two Numbers Mean?

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
MethodIdeaNotes
Temp variableSave, overwrite, restoreClearest language-agnostic answer
Tuple unpacka, b = b, aMost Pythonic
XORThree ^= stepsIntegers only; interview trick

How to Swap Two Numbers in Python

Four clear steps for the temp method — then Pythonic and XOR variants.

  1. Store the first value in temp.
  2. Copy the second value into the first variable.
  3. Copy temp into the second variable.
  4. Or use a, b = b, a in real Python code; mention XOR only if asked.
MethodIdeaTimeBest for
Temp variabletemp = a; a = b; b = tempO(1)Interviews across languages
Tuple unpacka, b = b, aO(1)Everyday Python
XORa ^= b three timesO(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

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
Interview defaultUse a temporary variable
Temp stepstemp = a; a = b; b = temp
Pythonica, b = b, a
Equal valuesSwap still works; result unchanged
XORIntegers only — not for floats
Classic check5, 10 → 10, 5

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

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

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.

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

  1. temp = num1 saves 5 so it is not lost.
  2. num1 = num2 copies 10 into the first variable.
  3. num2 = temp restores the saved 5.
  4. Works for equals, negatives, and any assignable type.
  5. This is the answer to give first in interviews.

Example 2 — Swap Using Tuple Unpacking

Python evaluates the right-hand side first, then assigns both names at once.

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

  1. The right side builds the pair (num2, num1) first — values are frozen.
  2. Then num1 receives the old num2.
  3. And num2 receives the old num1.
  4. No named temp is required; Python handles the temporary packing.
  5. Prefer this in everyday Python; still mention the temp version in interviews.

Example 3 — Swap Without Temp (XOR Trick)

Three XOR steps trade bit patterns. Keep it 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

  1. a ^= b mixes both bit patterns into a.
  2. b ^= a recovers the original a into b.
  3. a ^= b recovers the original b into a.
  4. The a != b guard is a safe habit when mentioning aliasing edge cases.
  5. Prefer temp or tuple unpack for readability; mention XOR only if asked.

Edge Cases & Pitfalls

Check these before calling the solution done.

Equal

Same values

Swap still runs; both variables keep the same number.

XOR

Integers only

Bitwise XOR is not for floats or general objects. Temp and tuple unpack work more broadly.

Order

a = b first loses a

Without a temp (or packing), a = b then b = a makes both equal to the old b.

Readability

Temp or unpack

Lead with temp in interviews; use a, b = b, a in real Python. Treat XOR as optional.

Time and Space Complexity

ProgramTimeExtra space
Temp variableO(1)O(1)
Tuple unpackO(1)O(1)
XORO(1)O(1)

A swap touches a fixed number of variables — constant time and space.

Key Takeaways

  • Goal: exchange the values stored in two variables.
  • Interview: temp = a; a = b; b = temp
  • Python: a, b = b, a is the everyday choice.
  • Test set: (5,10) → (10,5); (4,4) stays; negatives work with temp.

One line: save one value, overwrite it, then put the saved value into the other variable — or write a, b = b, a.

Frequently Asked Questions

After a swap, the first variable holds the old second value, and the second holds the old first value.
Not always. Tuple unpacking (a, b = b, a) is the most Pythonic way. A temporary variable is still the clearest language-agnostic interview answer.
Swap still works; both values remain the same.
Yes. Temp and tuple unpacking work for any values. XOR also works for integers.
All common swap methods are O(1) time and O(1) extra space.

Next: Triangular Number

Check whether a number sits in the sequence 1, 3, 6, 10, …

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.

10 people found this page helpful