Python Program to Swap Two Numbers Using XOR
a and b in Python using XOR with: a = a ^ b; b = a ^ b; a = a ^ b.Examples
How to Think About It
Algorithm
Code
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}")
Dry Run
Let's trace swapping a=5 and b=10 using XOR.
Initial values
a=5 (0101), b=10 (1010)
a = a ^ b
a = 0101 ^ 1010 = 1111 (15)
b = a ^ b
b = 1111 ^ 1010 = 0101 (5) (original a)
a = a ^ b
a = 1111 ^ 0101 = 1010 (10) (original b)
| Step | a (binary) | b (binary) | a (decimal) | b (decimal) |
|---|---|---|---|---|
| Initial | 0101 | 1010 | 5 | 10 |
| a = a ^ b | 1111 | 1010 | 15 | 10 |
| b = a ^ b | 1111 | 0101 | 15 | 5 |
| a = a ^ b | 1010 | 0101 | 10 | 5 |
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
a = 5 b = 10 temp = a a = b b = temp print(f"After swap: a={a}, b={b}")
a = 5 b = 10 a, b = b, a print(f"After swap: a={a}, b={b}")
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| XOR Swap | O(1) | O(1) | Memory-constrained environments |
| Temporary Variable | O(1) | O(1) | Clarity and simplicity |
| Tuple Unpacking | O(1) | O(1) | Pythonic and readable code |