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.
a = 5b = 2a = 2b = 5Interactive 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.
Four ways to swap two values
| Method | Main idea | Best use |
|---|---|---|
| Temporary variable | Save one value before overwriting it | Best for learning the logic |
| Multiple assignment | a, b = b, a | Cleanest and most Pythonic |
| Addition and subtraction | Preserve the total while separating values | Useful as a mathematical exercise |
| XOR | Use bitwise operations | Useful 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.
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
- Change the initial values and confirm that every two-variable method still works.
- Swap two strings, such as
"Champak"and"Deepak", using multiple assignment. - Rotate three values in the opposite direction.
- Ask the user to enter the values with
input(). - 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
0 Comments
Please comment