Swap two variables in one line in using Python?


We will learn how to swap two variables in one line. Let’s say the following is our input −

a = 10
b = 5

The following is our output after swap −

a = 5
b = 10

Swap two variables in one line using comma operator

Using the comma operator, you can create multiple variables in a single line. The same concept is considered here and the variable values are swapped −

Example

a = 5; b = 10; print("Variable1 = ",a); print("Variable2 = ",b); # Swap two variables in one line using comma operator a, b = b, a print("\nVariable1 (After Swapping) = ",a); print("Variable2 (After Swapping) = ",b);

Output

Variable1 =  5
Variable2 =  10

Variable1 (After Swapping) =  10
Variable2 (After Swapping) =  5

Swap two variables using multiplication and division operator

Swapping variables in Python can be achieved using the operators −

Example

a = 5; b = 10; print("Variable1 = ",a); print("Variable2 = ",b); # Swap two variables a = a * b b = a / b a = a / b print("\nVariable1 (After Swapping) = ",a); print("Variable2 (After Swapping) = ",b);

Output

Variable1 =  5
Variable2 =  10

Variable1 (After Swapping) =  10.0
Variable2 (After Swapping) =  5.0

Swap two variables using XOR

Swapping variables in Python can be achieved using the XOR operator −

Example

a = 5; b = 10; print("Variable1 = ",a); print("Variable2 = ",b); # Swap two variables a = a ^ b b = a ^ b a = a ^ b print("\nVariable1 (After Swapping) = ",a); print("Variable2 (After Swapping) = ",b);

Output

Variable1 =  5
Variable2 =  10

Variable1 (After Swapping) =  10
Variable2 (After Swapping) =  5

Updated on: 11-Aug-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements