Python Program to Swap Two Variables: Beginners Guide
Summary:
Problem-solving in python is easy as compared to other languages, thanks to its simplicity. This is the main reason for its popularity. In this guide, we will see the program to swap two variables in python with and without using any third variable.
Problem Statement
Write a Python program to swap two variables.
Example:
Suppose a=2
and b=7
then after the swap, the values will be a=7
and b=2
.
Python Program to Swap Variables
There are generally two ways to swap variables in any language.
- Using temporary Variable
- Without using the temporary Variable
Using Temporary Variable
a=2
b=7
#Take temporary variable 'temp'.
#Store value of a in b.
#Store value of temp (originally taken from a) into b.
temp = a
a = b
b = temp
print(a) #7
print(b) #2
This is a traditional way to swap values of two variables in any language but not ‘pythonic way to solve the problem’.
Without using temporary/third Variable
This is one of the hottest brain-twisting questions in programming interviews. But Python programmers need not think much about the solution.
a=2
b=7
a,b=b,a
print(a) #7
print(b) #2
As simple as it. You can use this code to swap two variables in one line in python. This is ‘pythonic way’ to swap two variables.
Addition and Subtraction
There is another solution which the interviewer may expect from you.
Note: This method only works for numbers.
a=2
b=7
a=a+b #a=2+7=>9
b=a-b #b=9-7=>2
a=a-b #a=9-2=>7
print(a) #7
print(b) #2
Using Division and Multiplication
Note: This method works only with numbers and integer is converted to float.
a=2
b=7
a = a * b #a= 2*7 => 14.0
b = a / b #b= 14.0/7 => 2.0
a = a / b #a= 14.0/2.0 => 7.0
print(a) #7.0
print(b) #2.0
These were the most common ways to swap values of variables in Python. If you have any problem or better solution, share them in comments.
You may also like:
Join Our Youtube Channel
Subscribe