July 11, 2022 | Posted in Python
Let us say we have two integers a and b with a’s value equal to 1 and b’s value equal to 2. And we want to swap them without needing the temporary variable in Python.
The simplest and pythonic way to solve this swap problem is as follows:
a = 1
b = 2
a, b = b, a
We can not use this swapping technique in another programing language. However, here is another solution to swap data between two variables and this algorithm can be used in any programing language.
a = 1
b = 2
a = a + b
b = a - b # this will act like (a+b) - b, and now b equals a.
a = a - b # will act like (a+b) - a, and now an equals b.