📚
Swap Variables
Swapping Two Variables
Imagine you have two boxes: one labeled
a10b20a20b10In most programming languages, you'd need a third temporary box. But Python has an elegant one-line trick:
a = 10 b = 20 a, b = b, a # Swap! print(a) # → 20 print(b) # → 10
How Does This Work?
The line
a, b = b, a- ◆Right side first: Python reads and creates a temporary pair
b, a(20, 10) - ◆Then assigns: It puts into
20andainto10b
This is called tuple unpacking — Python packages the values, then unpacks them into the variables. You don't need to understand tuples yet; just know this trick works!
💡💡 This is Pythonic: Python has many elegant shortcuts like this. Writing code "the Python way" is called being Pythonic.
main.pySandbox
main.py
Ctrl + Enter