Skip to content

Swap Two Variables ๐Ÿ”„

Mentor's Note: In many languages, swapping is a 3-step process. In Python, we can do it in a single, beautiful line! ๐Ÿ’ก


๐ŸŒŸ The Scenario: The Book Exchange ๐Ÿ“š

Imagine Alice has a Science book and Bob has a History book. They want to swap.

  • The Logic (Classic): They need a third person (Temp) to hold Alice's book while she takes Bob's. ๐Ÿ“ฆ
  • The Logic (Pythonic): They just hand the books to each other at the exact same time! โœจ

๐Ÿ’ป Implementation: The Swap Lab

# ๐Ÿ›’ Scenario: Direct Exchange
# ๐Ÿš€ Action: Using Tuple Unpacking

a = 10
b = 20

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

# โœจ The Magic Line
a, b = b, a

print(f"After:  a={a}, b={b}")
# ๐Ÿ›’ Scenario: Using a Middleman
# ๐Ÿš€ Action: Using a Temporary Variable

a = 10
b = 20

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

# ๐Ÿ“ฆ 1. Save 'a' in a temporary box
temp = a
# ๐Ÿ“ฆ 2. Put 'b' into 'a'
a = b
# ๐Ÿ“ฆ 3. Put the saved value into 'b'
b = temp

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

๐Ÿ“– Key Concepts

  • Tuple Unpacking: a, b = b, a is a unique Python feature. It evaluates the right side first (creating a tuple of values) and then assigns them to the variables on the left.
  • Temporary Variable: The temp variable acts as a "buffer" so that the original value of the first variable isn't lost when the second one is assigned to it.

๐Ÿ“Š Sample Dry Run (Classic Method)

Step a b temp Description
Start 10 20 - Initial values
temp = a 10 20 10 a is safe in temp ๐Ÿ“ฅ
a = b 20 20 10 a now has b's value ๐Ÿ”„
b = temp 20 10 10 b gets the saved value ๐Ÿ“ค

๐ŸŽฏ Practice Lab ๐Ÿงช

Task: Three-Way Swap

Task: Given x=1, y=2, z=3. Swap them so that x=2, y=3, and z=1. Hint: Can you do it in one line using the Pythonic way? x, y, z = ... ๐Ÿ’ก

Quick Quiz

Quick Quiz

Why is a temporary variable needed in the classic method? - [ ] To make the code run faster. - [x] To prevent the first value from being overwritten and lost. - [ ] Because Python requires it. - [ ] To save memory.

Explanation: Without temp, if you do a = b, the original value of a is gone forever. You need to store it somewhere before replacing it.


๐Ÿ“ˆ Learning Path