Python Program to Swap Two Variables – 2023

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.

And in this way, we can swap x and y sing a temp variable. But here we are using extra memory to store the temp variable. We have one more way of swapping x and y without using the temp variable and that is demonstrated below.

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

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 521

Leave a Reply

Your email address will not be published. Required fields are marked *