With Python, we can easily swap two values between variables. The easiest way is to use tuple unpacking.
x = 2
y = 3
x, y = y, x
print(x)
print(y)
#Output:
3
2
You can also use a temporary variable to swap the values of two variables.
x = 2
y = 3
temp_var = x
x = y
y = temp_var
print(x)
print(y)
#Output:
3
2
When working with variables in Python, being able to change the values of variables easily is important.
One such change is swapping the values between two variables.
We can easily swap values of two variables in Python. To swap values you can use a temporary variable, or the easiest way is to swap values is with tuple unpacking.
Below is an example in Python of how to swap the values of two variables using tuple unpacking.
x = 2
y = 3
x, y = y, x
print(x)
print(y)
#Output:
3
2
Swap Values in Python with Temporary Variable
We can also swap values in Python with the use of a temporary variable.
In this method, we first store the first value in the temporary variable, set the first variable equal to the second variable, and then set the second variable equal to the temporary variable.
After swapping the values, we won’t be using the temporary variable, making this method less optimal than the method of tuple unpacking.
Below is how to swap two variables in Python with a temporary variable.
x = 2
y = 3
temp_var = x
x = y
y = temp_var
print(x)
print(y)
#Output:
3
2
How to Swap Two Items in a List Using Python
We can also swap items in a list using Python using the same tuple unpacking method of how to swap two variables.
Below is an example in Python of how to swap two items in a list.
def swapPositions(lst,position1, position2):
lst[position1], lst[position2] = lst[position2], lst[position1]
return lst
print(swapPositions([0,1,2,3,4,5],2,3))
#Output:
[0,1,3,2,4,5]
Hopefully this article has been useful for you to learn how to swap two values with Python.