After the roaring success of my first Python_PLUS_PLUS video on "Swapping Variable Values in Python", it seemed logical to follow it up with a written version so you didn't have listen to my voice.
In this tutorial, I'll be using Python 3.8 with the IDLEX extensions installed.
Swapping variable values in Python or indeed in any programming language really isn't that complicated as long as you remember that when you overwrite a variable value you the original value is lost, forever.
For example, let's save the value 6 in the computers memory and assign it the identifier x ...
>>> x = 6
Now let's also save the value 9 in the computers memory and assign it the identifier y ...
>>> y = 9
OK, let's print these values out, just to make sure that they've saved properly ...
>>> print(x) 6 >>> print(y) 9
Cool. Now, if we wish to swap these two values over, one approach we could take would be to set x equal to y and then y equal to x. Let's try that ...
>>> x = y >>> y = x
Now, let's print out the values of x and y and see what's happened ...
>>> print(x) 9 >>> print(y) 9
Oh. As you can see, they are both the same and we've lost the original value of x. Let's set x back to its original value ...
x = 6
To do the swap properly, we need a variable to hold the value of x temporarily whilst we swap it for the value of y and then we set y back to the value of the temporary variable.
>>> temp = x >>> x = y >>> y = temp
So, now let's print out the values of x and y ...
>>> print(x) 9 >>> print(y) 6
Yeah, that's right, we've swapped them over.
There is a shortcut in Python which you can use which is super cool but it might confuse programmers if they aren't familiar with what you have done.
x, y = y, x
Good eh? M