Swap Two Variables

Swap the values of two variables using a temporary variable and Python's tuple unpacking.

PythonBeginner

What You'll Learn

  • Swapping values using a temporary variable
  • Using Python tuple unpacking for swapping
  • Understanding multiple assignment in Python
Python
# Swapping using a temporary variable
a = 5
b = 10

temp = a
a = b
b = temp

print("After swapping (using temp): a =", a, "b =", b)

# Swapping using Python tuple unpacking
x = 5
y = 10

x, y = y, x

print("After swapping (tuple unpacking): x =", x, "y =", y)

Output

After swapping (using temp): a = 10 b = 5
After swapping (tuple unpacking): x = 10 y = 5

Swap Two Variables in Python

This program demonstrates two ways to swap the values of variables in Python.

Method 1: Using a Temporary Variable

This is the traditional method used in most programming languages:

python
temp = a
a = b
b = temp

How it works:

  1. Store a in temp.
  2. Assign b to a.
  3. Assign temp to b.

This method is clear and easy to understand, especially for beginners.

Method 2: Using Tuple Unpacking (Pythonic Way)

Python has a special feature called tuple unpacking that makes swapping very concise:

python
x, y = y, x

How it works:

  • Python creates a tuple on the right side: (y, x)
  • Then unpacks it into the variables on the left: x, y
  • This happens in a single line!

This is the Pythonic (idiomatic Python) way to swap variables.

Key Takeaways

1

Temporary variable method works in all languages

2

Tuple unpacking is Python-specific and more concise

3

Both methods achieve the same result

4

Tuple unpacking is preferred in Python for readability

Step-by-Step Breakdown

  1. 1Initialize two variables with sample values.
  2. 2Swap them using a temporary variable and print the result.
  3. 3Reinitialize two variables.
  4. 4Swap them using tuple unpacking.
  5. 5Print the swapped values again.