Given two variables we create a Python program to swap their values.
In this lesson, therefore, we will implement a simple algorithm for swap variables in Python, in order to also introduce the concept of multiple assignment.
Given in input the values of two variables a and b, we want to swap their values, so that at the end a contains the value of b and b that of a.
So here’s an example:
If a = 5 and b = 4, we want that at the end of our algorithm it is a = 4 and b = 5.
So let’s think about a possible solution! Surely, to exchange these values, a possible solution could be to use a temporary support variable.
I call this third variable temp, and I proceed like this:
temp = a # in the temp variable I store the value of a
a = b #in a I store the value of the variable b
b = temp #in b I store the value of the temp variable which contains the value of a
So I get the exchange of values. In the end, in fact, I will have: a = 4 and b = 5.
But beware, there is another way to swap variables in Python.
I, therefore, introduce the concept of multiple assignment.
Swap Python – Multiple assignment
With multiple assignment in python, you can assign multiple variables at a time.
So for example:
a = b = 5
In this case both a and b take the value of 5.
Or another assignment I can make is this:
a, b = 5, 4
In this way I assign the value 5 to a and the value 4 to a b.
If I write later:
a, b = b, a
I get the exchange of the two values.
Swap program in Python
Here is the complete solution:
a = int (input (‘Insert a:’))
b = int (input (‘Insert b:’))
print (‘The values entered are a:’, a, ‘and b:’, b)
print (‘Now exchange the values’)
a, b = b, a
print (‘The values exchanged are a:’, a, ‘and b:’, b)
a = int (input ('Insert a:'))
b = int (input ('Insert b:'))
print ('The values entered are a:', a, 'and b:', b)
print ('Now exchange the values')
a, b = b, a
print ('The values exchanged are a:', a, 'and b:', b)
This is just a very simple example of swapping variables in python with multiple assignment.
Conclusion
In this lesson we have dealt with the study of swap variables in Python, in the next lessons we will apply this concept to many practical exercises.
Some useful links
How to find the maximum of N numbers