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.

  1. Using a temporary variable:
a = 5
b = 7

temp = a
a = b
b = temp

print("a =", a)
print("b =", b)
  1. Using tuple unpacking:
a = 5
b = 7

a, b = b, a

print("a =", a)
print("b =", b)
  1. 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.

Tags:

related content