Learn With Champak

Swapping Variables in Python

Learn several ways to exchange two values and rotate three values. Run, change and test every example directly inside the embedded Python editors.

What does swapping mean?

Swapping means exchanging the values stored in variables. If a = 5 and b = 2, then after swapping, a should contain 2 and b should contain 5. This simple problem teaches assignment, expressions, temporary storage and careful tracking of changing values.

Before swapping
a = 5
b = 2
After swapping
a = 2
b = 5

Interactive program 1: swapping two variables

This program demonstrates multiple techniques: a temporary variable, Python's multiple assignment, arithmetic operations and XOR. Click Run inside the editor and compare the output produced by each method.

Open the two-variable program in a new tab

Four ways to swap two values

MethodMain ideaBest use
Temporary variableSave one value before overwriting itBest for learning the logic
Multiple assignmenta, b = b, aCleanest and most Pythonic
Addition and subtractionPreserve the total while separating valuesUseful as a mathematical exercise
XORUse bitwise operationsUseful for understanding integers and bits

Recommended in real Python programs: use a, b = b, a. It is short, readable and works with many types of values—not only integers.

Interactive program 2: rotating three variables

With three variables, we usually perform a rotation rather than a simple pairwise swap. For example, the old value of c moves to a, the old value of a moves to b, and the old value of b moves to c.

Open the three-variable program in a new tab

The simplest Python solution

Python evaluates the values on the right-hand side first and then assigns them to the variables on the left-hand side. That makes swapping and rotation remarkably clear:

# Swap two variables
a, b = b, a

# Rotate three variables: c → a, a → b, b → c
a, b, c = c, a, b

Practice challenges

  1. Change the initial values and confirm that every two-variable method still works.
  2. Swap two strings, such as "Champak" and "Deepak", using multiple assignment.
  3. Rotate three values in the opposite direction.
  4. Ask the user to enter the values with input().
  5. Try to rotate four variables in a single Python statement.

Learn by changing the code

Do not only read the programs. Run them, alter the starting values, predict the result and then verify your prediction. That is how programming logic becomes strong.

Learn With Champak — practical Python, DSA and AI/ML learning for students.

Learn online with Champak Roy