Tutorialspoint
Problem
Solution
Submissions

Swap Two Variables Without a Temporary Variable

Certification: Basic Level Accuracy: 78.38% Submissions: 185 Points: 5

Write a Python program that swaps the values of two variables without using a temporary variable.

Example 1
  • Input: a = 5, b = 10
  • Output: a = 10, b = 5
  • Explanation:
    • Step 1: Add the values of both variables: a = a + b = 5 + 10 = 15.
    • Step 2: Set b equal to a minus b: b = a - b = 15 - 10 = 5.
    • Step 3: Set a equal to a minus b: a = a - b = 15 - 5 = 10.
    • Step 4: Now, a = 10 and b = 5, successfully swapped without using a temporary variable.
Example 2
  • Input: a = "hello", b = "world"
  • Output: a = "world", b = "hello"
  • Explanation:
    • Step 1: Using Python's multiple assignment feature: a, b = b, a.
    • Step 2: This assigns b's value ("world") to a, and a's value ("hello") to b simultaneously.
    • Step 3: Now, a = "world" and b = "hello", successfully swapped without a temporary variable.
Constraints
  • -10^6 ≤ integer values ≤ 10^6
  • 1 ≤ len(string) ≤ 100 characters
  • Time Complexity: O(1)
  • Space Complexity: O(1)
NumberVariables and Data TypesPwCKPMG
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use arithmetic operations (for numbers): a = a + b; b = a - b; a = a - b
  • Use XOR operation (for integers): a = a ^ b; b = a ^ b; a = a ^ b
  • Use tuple unpacking: a, b = b, a
  • Use array/list assignment: [a, b] = [b, a]

The following are the steps to Swap Two Variables Without a Temporary Variable:

1. Define a function `swap_numbers(a, b)` that takes two numbers.

2. Use `a, b = b, a` to swap the values without a temporary variable.

3. Return the swapped values.

4. Call `swap_numbers(5, 10)` and store the result.

5. Print the swapped numbers.

Submitted Code :