How to Swap Two Variables in One Line Python Easily
In Python, you can swap two variables in one line using
a, b = b, a. This uses tuple unpacking to assign the values simultaneously without needing a temporary variable.Syntax
The syntax to swap two variables a and b in one line is:
a, b = b, a
Here, b, a creates a tuple of the values, and a, b unpacks them back into the variables, effectively swapping their values.
python
a, b = b, a
Example
This example shows swapping two numbers using one line of code:
python
a = 5 b = 10 print(f"Before swap: a = {a}, b = {b}") a, b = b, a print(f"After swap: a = {a}, b = {b}")
Output
Before swap: a = 5, b = 10
After swap: a = 10, b = 5
Common Pitfalls
Some beginners try to swap variables using a temporary variable in multiple lines, which is longer and less elegant:
temp = a
a = b
b = temp
Another mistake is trying to swap without unpacking, like a = b; b = a, which does not swap but copies the same value to both variables.
python
a = 1 b = 2 # Wrong way - does not swap # a = b # b = a # Correct one-line swap a, b = b, a
Quick Reference
Remember these tips for swapping variables in Python:
- Use
a, b = b, afor a clean one-line swap. - No need for a temporary variable.
- Works with any data types, not just numbers.
Key Takeaways
Use tuple unpacking
a, b = b, a to swap variables in one line.This method avoids temporary variables and is more readable.
It works with any data types, including strings and lists.
Avoid assigning variables separately without unpacking to prevent errors.
Swapping in one line makes your code cleaner and easier to maintain.