Swapping Two Variables in Python
The following example demonstrates how to swap the values of two variables entered by the user.
Example 1: Using a Temporary Variable
# User input x = input('Enter the value of x: ') y = input('Enter the value of y: ') # Create a temporary variable and swap temp = x x = y y = temp print('After swapping, the value of x is: {}'.format(x)) print('After swapping, the value of y is: {}'.format(y))
Output:
Enter the value of x: 2 Enter the value of y: 3 After swapping, the value of x is: 3 After swapping, the value of y is: 2
In this example, a temporary variable temp
is used to store the value of x
. The value of y
is then assigned to x
, and the value of temp
is assigned to y
, effectively swapping the two values.
Swapping Without a Temporary Variable
We can also swap variables without using a temporary variable, using a more elegant method in Python.
# User input x = input('Enter the value of x: ') y = input('Enter the value of y: ') # Swap without using a temporary variable x, y = y, x print('After swapping, the value of x is: {}'.format(x)) print('After swapping, the value of y is: {}'.format(y))
Output:
Enter the value of x: 1 Enter the value of y: 2 After swapping, the value of x is: 2 After swapping, the value of y is: 1
In this version, we use Python’s multiple assignment feature, which allows us to swap the values of x
and y
in one line: x, y = y, x
. This eliminates the need for a temporary variable.