DEV Community

Cover image for 4 ways to swap variable
Muhimen
Muhimen

Posted on

4 ways to swap variable

Do you remember the first code you ever wrote? If my calculations are right then it was a hello, world program, right? Hello, world is now a tradition of programming. Do you know what else is a programming tradition? Swapping two variables. Today, we will see 4 different ways to swap 2 variables.

1 Using a temporary variable

We store the value of any of the variables(suppose it's a) in the temporary variable. Then assign the value of b to a. At last assign the value of tmp to b.

a = 50
b = 40
tmp = a
a = b
b = tmp
Enter fullscreen mode Exit fullscreen mode

2 Without extra variable

This method works for python. I am not sure if the same applies to other languages as well(It should, except C++, C, C#).

a = 50
b = 5
a, b = b, a
Enter fullscreen mode Exit fullscreen mode

3 Without extra variable(math)

This method uses simple math to swap two variables. Keep in mind, we are working with math, so only integer, float or double will work(including long).

a = 5
b = 2
a = a*b
b = a//b
a = a//b
Enter fullscreen mode Exit fullscreen mode

Debuging mode:

>>>a = 5
>>>b = 2
>>>a = a * b ==> 10
>>>b = a / b => 10 / 2 ==> 5
>>>a = a / b => 10 / 5 ==> 2
Enter fullscreen mode Exit fullscreen mode

Side note: Instead of multiplication and division you can use addition and subtraction too. And check out for ZERO DIVISION ERROR.


4 Using a list

In this case, we will add the value of a and b inside a list. And then extract the value in reverse order. Just like this.

a = 5
b = 2
ls = [a, b]
b, a = ls
Enter fullscreen mode Exit fullscreen mode

You can also use python tuples.


That's it. I hope that helps.

Top comments (2)

Collapse
 
muhimen123 profile image
Muhimen
  1. Maybe
  2. Everyone has different perspectives
  3. True. But you can apply addition and subtraction.