We have discussed different approaches to swap two integers without the temporary variable. How to swap into a single line without using the library function?
Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write “x, y = y, x”.
In Python, we can swap the values of two variables using a one-liner code. This is commonly known as the "Pythonic" way of swapping two variables.
Here is the Python program to swap two variables in one line:
a, b = b, a
In this code, we are using tuple packing and unpacking to swap the values of two variables. We first pack the values of a
and b
into a tuple, (b, a)
, and then unpack them into the variables a
and b
in reverse order. This effectively swaps the values of the two variables.
Here's an example of how to use this code to swap two variables:
a = 10 b = 20 print("Before swapping: a =", a, "b =", b) a, b = b, a print("After swapping: a =", a, "b =", b)
Output:
Before swapping: a = 10 b = 20 After swapping: a = 20 b = 10
In this example, we first set the values of a
and b
to 10 and 20, respectively. We then print their values before and after swapping using the print
function. Finally, we swap the values of a
and b
using the one-liner code, a, b = b, a
.