How To Swap Two Variables In One Line In Python

Swapping two variables is a foundational concept in computer programming. In Python, you can efficiently swap the values of two variables in a single line of code. In this tutorial, we’ll explore how to do this using tuple unpacking, a technique that makes swapping variables extremely concise and readable.

Step 1: Understand Tuple Unpacking

Before we dive into swapping two variables in a single line, it’s important to understand the tuple unpacking technique in Python. Tuples are immutable sequences of elements, enclosed in parenthesis. In Python, you can use tuple unpacking to assign multiple variables at once.

For instance, let’s examine the following code:

What this does is create a tuple with the elements 5 and 8, and then unpack those elements into the variables x and y. So after executing this line, x would contain the value 5, and y would contain the value 8.

Step 2: Swap Two Variables Using Tuple Unpacking

Now that we understand the tuple unpacking technique, let’s use it to swap the values of two variables in a single line. Here’s the syntax to perform this swap:

In this line, we create a tuple with the elements y and x, and then unpack those elements into the variables x and y. This effectively swaps the values of the two variables. Let’s look at an example to see this in action:

Initial values:

Swapping variables:

After the swap:

Output

x = 8
y = 5

As you can see, the values of x and y were swapped in a single line of code.

Full Code

Conclusion

Swapping two variables in a single line of code is an elegant and efficient technique in Python, thanks to its support for tuple unpacking. This method is concise and readable, making it a useful way to interchange variable values in your code. Now that you know how to swap two variables in one line in Python, you can apply this technique to optimize your programs and make them more efficient.