Skip to content

Swap Two Variables πŸ”„ΒΆ

Prerequisites: Variables & Data Types

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ΒΆ