How to Swap Three Values Cyclically in Python
Swapping variables is a standard programming task used in sorting algorithms and data manipulation. While many languages require a temporary variable to swap values without losing data, Python offers a concise feature called tuple unpacking that allows you to swap multiple variables in a single line.
This guide explains how to cyclically swap three variables (where a → b → c → a) efficiently.
Understanding the Swapping Logic
In this scenario, we want to perform a cyclic shift of values between three variables: a, b, and c.
- Original:
a=1, b=2, c=3 - Goal:
- New
bgets Olda(1) - New
cgets Oldb(2) - New
agets Oldc(3)
- New
- Result:
a=3, b=1, c=2
Method 1: Tuple Unpacking (The Pythonic Way)
Python evaluates the entire right-hand side of an assignment before assigning values to the left-hand side. This allows simultaneous swapping without temporary variables.
# Initial values
a, b, c = 1, 2, 3
print(f"Before: a={a}, b={b}, c={c}")
# ✅ Solution: Simultaneous Assignment
# Logic: a becomes c, b becomes a, c becomes b
a, b, c = c, a, b
print(f"After: a={a}, b={b}, c={c}")
Output:
Before: a=1, b=2, c=3
After: a=3, b=1, c=2
This works because Python creates a tuple (c, a, b) in memory first, and then "unpacks" that tuple into the variables on the left a, b, c.
Method 2: Using a Temporary Variable (Traditional)
In languages like C or Java, you typically need a temporary variable to hold a value so it isn't overwritten during the swap. This approach is valid in Python but less concise.
a, b, c = 1, 2, 3
# ✅ Solution: Using a temporary variable to hold 'a'
temp = a
a = c # a is now 3 (Old c)
c = b # c is now 2 (Old b)
b = temp # b is now 1 (Old a)
print(f"After Temp Swap: a={a}, b={b}, c={c}")
Output:
After Temp Swap: a=3, b=1, c=2
Handling User Input
To make the program dynamic, you often need to accept input from the console. Since input() returns a string, you must map the values to integers.
def swap_numbers():
print("Enter 3 numbers separated by space:")
# 1. Read string, 2. Split by space, 3. Convert to int, 4. Unpack
try:
a, b, c = map(int, input().split())
# Perform the swap
a, b, c = c, a, b
print("Swapped Result:")
print(a, b, c)
except ValueError:
print("Error: Please enter exactly 3 integers.")
if __name__ == "__main__":
swap_numbers()
Example Session:
Enter 3 numbers separated by space:
> 10 20 30
Swapped Result:
30 10 20
Common Pitfall: Sequential Assignment
A critical error beginners make is assigning variables one by one without a temporary variable. This leads to data loss.
a, b, c = 1, 2, 3
# ⛔️ Incorrect: Sequential assignment overwrites values prematurely
a = c # a becomes 3
b = a # b becomes 3 (because 'a' was just changed!)
c = b # c becomes 3
print(f"Broken Swap: a={a}, b={b}, c={c}")
Output:
Broken Swap: a=3, b=3, c=3
Never update variables sequentially if their new values depend on the old values of each other. Use Tuple Unpacking (Method 1) to ensure all values are read before any are written.
Conclusion
To swap three variables cyclically in Python:
- Use Tuple Unpacking:
a, b, c = c, a, bis the most efficient and readable method. - Avoid Sequential Assignment: Assigning lines one by one (
a=c,b=a) will overwrite data and fail. - Process Input: Use
map(int, input().split())to handle multiple inputs cleanly.