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
Before swapping: a = 5, b = 10 After swapping: a = 10, b = 5
How it works
temp = akeeps a copy of the first value, because the next line overwritesa.a = bcopies the second value intoa.b = tempputs the saved first value intob, completing the swap.- Without
temp, writinga = band thenb = awould leave both variables holding 10.
Other ways to write it
Using tuple unpacking
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises