Swapping variable values in Python
Coding with Python
🕑 This lesson will take about 5 minutes
Let's say that we want to swap the values of two variables - a common task in programming (often used when sorting values in lists). A common way of doing this is by using an additional variable that can temporarily store a value from one variable while the contents of two variables are being swapped, for example:
The code above would produce the following output:
a = 2
b = 1
Initially, the variable a stores the value 1 and the variable b stores the value 2. The temp variable takes the value in variable a and stores it. Then, variable a takes the value of variable b. Finally, variable b takes the value from the temp variable and stores it.
However, there is another method you can use in Python with just one line of code as shown in the example below.