DEV Community

Cover image for Python How-To: Swapping Variable Values With Python
dev_neil_a
dev_neil_a

Posted on

Python How-To: Swapping Variable Values With Python

Introduction

This how-to guide will highlight two methods that can be used in Python to swap the values of two variables around.

With that said, let's start with the first method.

Method One: Swapping Variable Values With A Third Variable

The first step is to create two variables and assign each a value. For example:

a = "Hello"
b = "World"

print(a, b)
Enter fullscreen mode Exit fullscreen mode

Output:

001

Now, to reassign the two variables with each others value, let's add a third variable into the mix:

c = a
a = b
b = c

print(a, b)
Enter fullscreen mode Exit fullscreen mode

Output:

002

Whilst this is a sound way of performing the reassignment of the two variables values, there is another method that may come up on interview questions that is a more preferred method, which leads us to method two.

Method Two: Swapping Variable Values Without A Third Variable

The second method that can be used to swap the values of two variables is to define b and a on the same line, followed by equals and then a, b. For example:

a = "Hello"
b = "World"

print(a, b)
Enter fullscreen mode Exit fullscreen mode

Output:

003

The output is exactly the same as the beginning of method one.

Now, let's swap the values of the two variables:

b, a = a, b

print(a, b)
Enter fullscreen mode Exit fullscreen mode

Output:

004

The output is exactly the same as in method one once the values of the two variables were swapped but this time, it was done with only the two original variables names.

Conclusion

The two methods shown are not the only methods to swap values between variables but they are the most likely to be used.

The methods can be used to swap various data types, including strings, integers and floats.

Thank you for reading and have a nice day!

Top comments (0)