This post shows how to swap two numbers in Python — a simple but frequently asked basic programming question, including Python's unique one-line trick for it.

Swap two numbers in Python:

Explanation:
Unlike many languages that need a temporary third variable, Python lets you swap two variables in a single line using tuple assignment: a, b = b, a. The right side is evaluated completely before either variable is reassigned, so no temporary variable is needed.


Python Program to Swap Two Numbers

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

a, b = b, a

print(f"After swapping: a = {a}, b = {b}")

Output:

Enter first number: 5
Enter second number: 10
After swapping: a = 10, b = 5

Try it yourself, and try writing the version with a temporary variable too, in our Code Runner.