DEV Community

Susmita Dey
Susmita Dey

Posted on • Edited on

3 3

Swapping Of Two Numbers In Python in One Line

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)
Enter fullscreen mode Exit fullscreen mode

Output:-

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

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.😊

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay