Bird
0
0

You want to swap the values of two variables a and b without using a temporary variable. Which of the following is the correct way in Python?

hard📝 Application Q8 of 15
Python - Variables and Dynamic Typing
You want to swap the values of two variables a and b without using a temporary variable. Which of the following is the correct way in Python?
Aa = a + b; b = a - b
Ba = b; b = a
Ca, b = b, a
Da = b; b = a + b
Step-by-Step Solution
Solution:
  1. Step 1: Understand Python tuple unpacking

    Python allows swapping variables in one line using tuple unpacking: a, b = b, a.
  2. Step 2: Check other options

    a = b; b = a assigns b to a, then a to b, which results in both having b's value. a = a + b; b = a - b performs the first two steps of an arithmetic swap but misses the last step, leaving a as the sum. a = b; b = a + b is incorrect and changes values incorrectly.
  3. Final Answer:

    a, b = b, a -> Option C
  4. Quick Check:

    Swap variables easily with a, b = b, a [OK]
Quick Trick: Swap variables with a, b = b, a [OK]
Common Mistakes:
MISTAKES
  • Overwriting variables before swap
  • Using incorrect math operations
  • Not using tuple unpacking

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes