Python program to swap variables

In this tutorial,we will see Python programs to swap two variables. In the first program we are swapping the variables using temporary variable and in the others programs we are swapping without using temporary variable.

x = 10 y = 20

1. Swapping of two variables using third variable:

temp = x x = y y = temp print("Value of x:", x) print("Value of y:", y)

2. Swapping two variables using simple built-in method:

left , right = right , left

x = 15 y = 20

print (“Before swapping: “)
print(“Value of x : “, x, ” and y : “, y)

# code to swap ‘x’ and ‘y’
x, y = y, x

print (“After swapping: “)
print(“Value of x : “, x, ” and y : “, y)

3. Swapping two variables using addition and subtraction:

Syntax:

x = x + y y = x - y x = x - y

x=10
y=15

print (“Before swapping: “)
print(“Value of x : “, x, ” and y : “, y)

x = x + y # x = 25, y = 15 y = x - y # x = 25, y = 10 x = x - y # x = 15, y = 10

print (“After swapping: “)
print(“Value of x : “, x, ” and y : “, y)

4. Swapping two variables using Multiplication and Division

x = x * y y = x / y x = x / y

Example:

x=7
y=9

print (“Before swapping: “)
print(“Value of x : “, x, ” and y : “, y)

x = x * y # x=63 y=9 y = x / y # x=63 y=7 x = x / y # x=9 y=7

print (“After swapping: “)
print(“Value of x : “, x, ” and y : “, y)