Swap Integers Without Temporary Variable in Python
It’s quite amusing to see how different variations of solutions for the same questions are thereby different individuals. From pretty ancient times maths has played a very vital role in civilizations. Not to mention how everything around us revolves mathematically. Now programming is more or less similar to that. It’s the second version of maths where to solve real-world problems you need to apply real-world mathematical concepts. However, as we’re talking about maths, how about writing a program to swap Integers. So today let’s write a simple program to Swap Integers Without Temporary Variable in Python.
What’s The Approach?
- Let us consider
yto be the numbers we want to swap with each other. Now the catch is to do this without using a temporary variable.
- Firstly we’ll store the addition of two variables in, one of the variables. That is,
x = x +y.
- Now, we will subtract the value of
y from xand assign this new value to
y = x -y this way we’ll store the value of variable x into variable y.
- Next, we’ll again subtract the value of y from x and assign this new value to
x = x - yby doing this we’ll store the value of variable y into x.
- After the above two instructions finish executing we’ll print the values of x &
Also Read: Print Sum of Digits in Given Number using Python
Python Program To Swap Integers Without Temporary Variable
x = 10, y = 5
x = 5, y = 10