How to quickly swap Variables Values in python
I'm going to show you how we can swap the value of two variables in one line in Python now without knowing this trick the way that we usually go about swapping variables is something like this :
I'm going to show you how we can swap the value of two variables in one line in Python now without knowing this trick the way that we usually go about swapping variables is something like this :
a=65
b=45
Temp=a
a=b
b=temp
Print(a,b)
we start by creating a temp variable that’s equal to one of the variables in this case a then we can reassign a's value to BB and when we resize V we're assign that to the temp variable so that we get the original value of a now this works fine if I print this out you can see that does indeed change our values to be 45 and 65 but this is not very nice and we want to do this
Now the Python way to do this is just do
a,b=b,a
Print(a,b)
and this will perform the swab for you automatically so when we do that, and I run the program you can see we are still indeed swapping the variables
this works with any number of variables I can add the variable c and then :
a=54
b=65
c= 100
and then maybe we will swap this process completely, so I'll write
a,b,c=b,c,a
print(a,b,c)
You see it's very easy using python langage then other like c,java ,etc.
When we do that we can print out a,b,c and you can see that this does indeed work and we can swap that many variables.
For more tips like this you can read this book :