Swap two variables in one line in using Python?

Python provides several ways to swap two variables in a single line. The most Pythonic approach uses tuple unpacking, but you can also use arithmetic or bitwise operators ?

Using Tuple Unpacking (Recommended)

Python's tuple unpacking allows you to swap variables in one elegant line using the comma operator ?

a = 5
b = 10

print("Before swapping:")
print("a =", a)
print("b =", b)

# Swap two variables in one line using tuple unpacking
a, b = b, a

print("\nAfter swapping:")
print("a =", a)
print("b =", b)
Before swapping:
a = 5
b = 10

After swapping:
a = 10
b = 5

Using Arithmetic Operations

You can swap variables using multiplication and division, though this method has limitations with zero values ?

a = 5
b = 10

print("Before swapping:")
print("a =", a)
print("b =", b)

# Swap using arithmetic operations
a = a * b
b = a / b
a = a / b

print("\nAfter swapping:")
print("a =", a)
print("b =", b)
Before swapping:
a = 5
b = 10

After swapping:
a = 10.0
b = 5.0

Using XOR Operator

The XOR bitwise operator can swap integers without using temporary variables ?

a = 5
b = 10

print("Before swapping:")
print("a =", a)
print("b =", b)

# Swap using XOR operator
a = a ^ b
b = a ^ b
a = a ^ b

print("\nAfter swapping:")
print("a =", a)
print("b =", b)
Before swapping:
a = 5
b = 10

After swapping:
a = 10
b = 5

Comparison

Method Works with Advantages Disadvantages
Tuple Unpacking Any data type Readable, Pythonic None
Arithmetic Numbers only No extra memory Fails with zero, float precision
XOR Integers only No extra memory Only integers, less readable

Conclusion

Use tuple unpacking a, b = b, a for swapping variables in Python as it's the most readable and works with any data type. Avoid arithmetic and XOR methods unless you have specific constraints requiring them.

Updated on: 2026-03-25T05:53:05+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements