Python Program to Swap Two Variables without using Third Variable
In this Python programming, we will see how to swap two values without temporary variable and with temporary variables.
Suppose x and y are the two variables. We want to swap the values of these two variables.
How to Write a Python Program to Swap Two Variables?
Here is the program you can use to swap two values using the third variable.
x = 5 y = 10 print "The value of x before swapping:", x print "The value of y before swapping:", y # create a temporary variable 'temp' # swap two values from two different variables temp = x x = y y = temp print "The value of x after swapping:", x print "The value of y after swapping:", y
Here we save the value of x in a temp variable. Overwrite value of x with the value of y. Replace the value of y by temp variable.
But Python makes the thing simple. I mean very simple.
Write a Python Program to Swap Two Variables without using Third Variable:
Here is a simple line of code that works for you.
x, y = y, x
You can check out the complete program for swapping two values without using a temporary variable.
x = 5 y = 10 print "The value of x before swapping:", x print "The value of y before swapping:", y # No need of temporary variable # swap the values x, y = y, x print "The value of x after swapping:", x print "The value of y after swapping:", y
Note: As Python uses dynamic data type. This program will work to swap any types of data values such as string, int, float. In the above program, I am using two numeric data type variables for swapping.
Python program to swap two variables without using third variable is most efficient as it does not use any temporary variable. Always prefer to write efficient code which takes less memory in every project.
If you have any other Python trick to swap two variables without using third variable, write in the comment section below.
Comments
Rajesh
Python is really interesting, nice and super.
Aniruddha Chaudhari
Absolutely!
Pythos is Gem 🙂
Chris
The statement ‘x, y = y, x’ does not mean that an intermediate hidden variable is not used.
Actually, you can swap two variables without extra register by the binary operation ‘xor’:
Aniruddha Chaudhari
Yeah, we can do that as well.
There are also some more other techniques to swap two numbers without a third variable.
We can also use addition-subtraction, multiplication-division operations as well to swap two numbers.