How to swap two numbers in Python
Published on Aug. 22, 2023, 12:16 p.m.
There are multiple ways to swap two numbers in Python.
- Using a temporary variable:
a = 5
b = 7
temp = a
a = b
b = temp
print("a =", a)
print("b =", b)
- Using tuple unpacking:
a = 5
b = 7
a, b = b, a
print("a =", a)
print("b =", b)
- Using bitwise XOR operator (not recommended for readability reasons):
a = 5
b = 7
a ^= b
b ^= a
a ^= b
print("a =", a)
print("b =", b)
All three methods produce the same output:
a = 7
b = 5
Note that the second method is the most pythonic and readable way to swap two numbers in Python.