0
0
PythonProgramBeginner · 2 min read

Python Program to Swap Two Numbers Using XOR

You can swap two numbers a and b in Python using XOR with: a = a ^ b; b = a ^ b; a = a ^ b.
📋

Examples

Inputa=5, b=10
OutputAfter swap: a=10, b=5
Inputa=0, b=0
OutputAfter swap: a=0, b=0
Inputa=123, b=456
OutputAfter swap: a=456, b=123
🧠

How to Think About It

To swap two numbers without using a temporary variable, use the XOR operator which flips bits where the bits differ. By applying XOR three times in a specific order, the values get exchanged without extra space.
📐

Algorithm

1
Take two numbers a and b.
2
Set a to a XOR b.
3
Set b to a XOR b (which is original a).
4
Set a to a XOR b (which is original b).
5
Now a and b are swapped.
💻

Code

python
a = 5
b = 10
print(f"Before swap: a={a}, b={b}")
a = a ^ b
b = a ^ b
a = a ^ b
print(f"After swap: a={a}, b={b}")
Output
Before swap: a=5, b=10 After swap: a=10, b=5
🔍

Dry Run

Let's trace swapping a=5 and b=10 using XOR.

1

Initial values

a=5 (0101), b=10 (1010)

2

a = a ^ b

a = 0101 ^ 1010 = 1111 (15)

3

b = a ^ b

b = 1111 ^ 1010 = 0101 (5) (original a)

4

a = a ^ b

a = 1111 ^ 0101 = 1010 (10) (original b)

Stepa (binary)b (binary)a (decimal)b (decimal)
Initial01011010510
a = a ^ b111110101510
b = a ^ b11110101155
a = a ^ b10100101105
💡

Why This Works

Step 1: XOR basics

The XOR operator ^ returns 1 only when bits differ, which helps encode differences between numbers.

Step 2: First XOR stores combined info

Setting a = a ^ b stores combined info of both numbers in a.

Step 3: Recover original a in b

Then b = a ^ b uses combined info to get original a value into b.

Step 4: Recover original b in a

Finally, a = a ^ b recovers original b value into a, completing the swap.

🔄

Alternative Approaches

Using a temporary variable
python
a = 5
b = 10
temp = a
a = b
b = temp
print(f"After swap: a={a}, b={b}")
Simple and clear but uses extra memory for temp variable.
Using tuple unpacking
python
a = 5
b = 10
a, b = b, a
print(f"After swap: a={a}, b={b}")
Pythonic and concise, no extra variables needed.

Complexity: O(1) time, O(1) space

Time Complexity

Swapping using XOR involves a fixed number of operations, so it runs in constant time.

Space Complexity

No extra memory is used besides the input variables, so space complexity is constant.

Which Approach is Fastest?

All methods run in constant time; tuple unpacking is most readable, XOR uses no extra memory, and temporary variable is simplest to understand.

ApproachTimeSpaceBest For
XOR SwapO(1)O(1)Memory-constrained environments
Temporary VariableO(1)O(1)Clarity and simplicity
Tuple UnpackingO(1)O(1)Pythonic and readable code
💡
Use XOR swap only when you want to avoid extra memory, but tuple unpacking is clearer in Python.
⚠️
Forgetting the order of XOR operations or reusing variables incorrectly can cause wrong results.