Python program to swap variables without third variable

In this tutorial,we will see without third variable.

1. 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)

2. 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)

3. 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)