Swap Two Numbers in Python

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 3 Code Examples
Variables

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

Live result
Press "Swap".

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 = temp
1

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

BeforeAfter
5, 1010, 5
0, 33, 0
-4, 2020, -4
7, 77, 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

VersionTimeExtra space
Temp swapO(1)O(1)
Tuple swapO(1)O(1)
XOR swapO(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.

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