Python Program to Swap Two Variables – 2022

Machine Learning Projects

Hey guys, in this blog we will see a Python Program to Swap Two Variables using 2 ways.

The first way is by using a temp variable and the second way is without using a temp variable.

Example 1: Using a temp variable

# Python Program to Swap Two Variables

x = 3
y = 6

print(f'x before swapping -> {x}')
print(f'y before swapping -> {y}')
print()

temp = x
x = y
y = temp

print(f'x after swapping -> {x}')
print(f'y after swapping -> {y}')

Output

x before swapping -> 3
y before swapping -> 6

x after swapping -> 6
y after swapping -> 3

Here we have used a temp variable to store x’s value. Then we overwrite x with y’s value and the last step is to overwrite y with temp/x’s value.

Example 2: Without Using a temp variable

# Python Program to Swap Two Variables

x = 3
y = 6

print(f'x before swapping -> {x}')
print(f'y before swapping -> {y}')
print()

x,y = y,x

print(f'x after swapping -> {x}')
print(f'y after swapping -> {y}')

Output

x before swapping -> 3
y before swapping -> 6

x after swapping -> 6
y after swapping -> 3

Here we haven’t used any temp variable, hence it is a more memory-efficient method.

Check out our other python programming examples

Leave a Comment

Your email address will not be published.