Editor

Python Program to Swap Two Variables

Beginner · Basics

Swapping two variables means exchanging their values: if a is 5 and b is 10, afterwards a is 10 and b is 5. This program uses a temporary third variable, the method taught in most textbooks, and the alternatives show the shorter Python way.

Program

swap_two_variables.py
a = 5 # or: a = int(input("Enter a: "))
b = 10 # or: b = int(input("Enter b: "))
print(f"Before swapping: a = {a}, b = {b}")
# Use a third variable to hold one value for a moment
temp = a
a = b
b = temp
print(f"After swapping: a = {a}, b = {b}")
Output
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5

How it works

  1. temp = a keeps a copy of the first value, because the next line overwrites a.
  2. a = b copies the second value into a.
  3. b = temp puts the saved first value into b, completing the swap.
  4. Without temp, writing a = b and then b = a would leave both variables holding 10.

Other ways to write it

Using tuple unpacking

Using tuple unpacking
a = 5
b = 10
print(f"Before swapping: a = {a}, b = {b}")
a, b = b, a
print(f"After swapping: a = {a}, b = {b}")
Output
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5

Python works out the right side b, a first, then assigns both values at once. This is the usual way to swap in Python.

Using addition and subtraction

Using addition and subtraction
a = 5
b = 10
a = a + b # a is now 15
b = a - b # b is now 5
a = a - b # a is now 10
print(f"After swapping: a = {a}, b = {b}")
Output
After swapping: a = 10, b = 5

This trick avoids a third variable but only works for numbers, so it mostly appears in exams and interviews.

Try it yourself

Add a third variable c and rotate the values so a gets the value of b, b gets c and c gets a.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises