Skip to content

How to Swap Three Values Cyclically in Python

Learn how to perform a cyclic swap of three variables in Python using tuple unpacking for efficient data manipulation without temporary variables.

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 b gets Old a (1)
    • New c gets Old b (2)
    • New a gets Old c (3)
  • 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.

a, b, c = 1, 2, 3

print(f"Before: a={a}, b={b}, c={c}")

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

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

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:")
    
    try:
        a, b, c = map(int, input().split())
        
        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

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

Conclusion

To swap three variables cyclically in Python:

  1. Use Tuple Unpacking: a, b, c = c, a, b is the most efficient and readable method.
  2. Avoid Sequential Assignment: Assigning lines one by one (a=c, b=a) will overwrite data and fail.
  3. Process Input: Use map(int, input().split()) to handle multiple inputs cleanly.
Navigation