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:
pythontemp = a a = b b = temp
How it works:
- Store
aintemp. - Assign
btoa. - Assign
temptob.
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:
pythonx, 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
- 1Initialize two variables with sample values.
- 2Swap them using a temporary variable and print the result.
- 3Reinitialize two variables.
- 4Swap them using tuple unpacking.
- 5Print the swapped values again.