Skip to content
Programs · Program 10-2

Q.Program 10-2: Write a program to swap two numbers without using a temporary variable.

Yanam BieapTextbookSubjective· 2mImportance★★★★★est
13% · 4/30 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

(num1, num2) = (num2, num1) packs the old values into a tuple first and then unpacks them crosswise — a swap with no temporary variable.

The idea. A traditional swap needs a third variable so one value is not overwritten before it is copied. Python's tuple assignment removes that need: the right side (num2, num1) is fully evaluated first (packing the current values), and only then unpacked into the left-side names. Both old values are already safe inside the tuple when reassignment happens.

Program 10-2:

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("Before swapping: num1 =", num1, ", num2 =", num2)
(num1, num2) = (num2, num1)        # tuple packing + unpacking does the swap
print("After swapping:  num1 =", num1, ", num2 =", num2)

Sample run:

Enter the first number: 5
Enter the second number: 10
Before swapping: num1 = 5 , num2 = 10
After swapping:  num1 = 10 , num2 = 5

Trace of the swap statement (inputs 5 and 10):

| Step | Action | num1 | num2 | …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.