How to swap two variables in Python?

Hi Folks!

In certain situations, you need to swap the variables in python scripts. So, let’s say a=5, and b=10. After swapping a=10 and b=5.

Before Swapping:
a=5
b=10
After swapping:
a=10
b=5

Now I’ll show you few interesting methods to swap two variables in python.

  1. Using a temporary variable
  2. Using comma operator (built-in method)
  3. Using Arithmetic operators

1.Using a temporary variable

Here we are saving the value to a temporary variable and then assigning it back. Let the temporary variable be “temp”.

a=100
b=50
temp=a // Here, we are storing the value of "a" to temp.
a=b // Assigning the value of b to a.
b=temp // Assigning the value of temp to b.
print(a)
print(b)

This method can be used with integers, floats and strings.

2. Using comma operator

It’s a pretty simple method to assign the variables.

a=100
b=50
a,b = b,a
print(a)
print(b)

This method also works with integers, floats and strings.

3. Using arithmetic operators

Using arithmetic operators, we can do it in two ways. We can use it as a combo of addition and subtraction; and as a combo of multiplication and division.

3a. Using the combination of addition and subtraction

a=10
b=2
a=a+b // a=10+2=12
b=a-b // b=12-2=10
a=a-b // a=12-10=2
print(a)
print(b)

3b. Using the combination of multiplication and division

a=100
b=20
a=ab // a=10020=2000
b=a/b // b=2000/20=100
a=a/b // a=2000/100=20
print(int(a))
print(int(b))

These methods work only with integers.

We can use method 2 and method 3 without having a separate variable. If you have any other methods, please comment it!!
Happy scripting!!

Post navigation

Heba Habeeb

Working as a Linux Server Admin, Infopark, Cochin, Kerala.

Leave a Reply

Your email address will not be published.