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¶
๐ Key Concepts¶
- Tuple Unpacking:
a, b = b, ais 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
tempvariable 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.