Python program to swap two variables

Description: Write a Python program to swap the values of two variables.

Rules and hints:

  • Do it first with a third (temporary) variable.
  • Then do it the Python way, in one line.

Python program to swap two variables

a = 10
b = 20
print("Before swap: a =", a, "b =", b)

a, b = b, a

print("After swap: a =", a, "b =", b)

Output:

Tutorials Class - Output Window

Before swap: a = 10 b = 20
After swap: a = 20 b = 10

How it works

  • The line a, b = b, a builds a tuple (b, a) and unpacks it into a and b.
  • In many other languages you need a third variable: temp = a, a = b, b = temp. That also works in Python.
  • Swapping works with any type, not only numbers.

Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.