Swapping Of Two Numbers In Python in One Line

Swapping Of Two Numbers In Python in One Line

ยท

1 min read

Do you know that using only just 1 line of code in Python you can Swap 2 numbers without using any third variable?

Let's see how can we do that...

Pre-requisites:-

  1. Download Python and Install it.
  2. Code Editor like Visual Studio Code or others of your choice where you can compile and run your python code.
  3. If you're using Visual Studio Code, then install this extension below. Python Extension

Code to Run:-

# taking input from the user
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
a, b = b, a  # Swapping two numbers
# printing values in one line after swapping
print("Output:-", a, b)

Output:-

PS D:\Coding> & C:/Python310/python.exe "d:/Coding Projects/Swap.py"
Enter a number: 5
Enter another number: 6
6 5

Another method is shown in this video:-


Hope this helps you. Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my YouTube Channel and connect on LinkedIn or Twitter. Also, feel free to support my work.๐Ÿ˜Š

ย