How to swap two numbers without using third variable in Python

Given problem statement is to “Swap two numbers without using any other third variable in Python“.

Swap two numbers without using amy third variable in Python

There are two simple ways to swap two numbers. This program is very simple because we are using basic operations like addition(+) ,subtraction(-) ,product(*) ,division(/) to swap the two numbers. In the first program, we are using product and division operations to swap the two numbers without any third variable.

Using product and division to swap two numbers in Python

By using product and division we can swap two numbers without any third variable.

a=10
b=20
print("before swapping: a= ",a," b= ",b)
a=a*b
#a becomes 200
b=a/b
#b becomes 10
a=a/b
#a becomes 20
print("after swapping: a= ",a," b= ",b)

OUTPUT:

before swapping: a= 10 b= 20
after swapping: a= 20 b= 10

In the above program “a” is taken as 10 and “b” is taken as 20. When we perform “a=a*b” ,”a” becomes 200. Then we perform “b=a/b” and “a=a/b”. Then “a” becomes 20 and “b” becomes 10.




But, there is a problem in the execution of these program in a special case. When any number of the two numbers given for swapping is ZERO(0), then the swapping is not possible. Except the zero case, it will work in every test case by swapping both given numbers. To overcome the above problem we can use Addition and subtraction method.

Using addition and subtraction swap two numbers

The way we follow to swap two numbers is easy to understand easily. This process is followed by addition and subtraction.

a=10
b=20
print("before swapping: a=" a,"b=" b)
a=a+b
#a becomes 30
b=a-b
#b becomes 10
a=a-b
#a becomes 20
print("after swapping: a=" a,"b= "b)

OUTPUT:

before swapping: a= 10 b= 20
after swapping: a= 20 b= 10

We take “a” as 10 and “b” as 20.First we perform “a=a+b” “a” becomes 30. We perform”b=a-b” and “a=a-b” to get “a” as 20 and “b” as 10.

We hope this will help you to learn how to swap two numbers without using a third variable in Python.

Also, read:


Leave a Reply

Your email address will not be published. Required fields are marked *