📚

Swap Variables

Swapping Two Variables

Imagine you have two boxes: one labeled

a
containing
10
, and one labeled
b
containing
20
. How do you swap them so
a
has
20
and
b
has
10
?

In 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
does two things simultaneously:

  1. Right side first: Python reads
    b, a
    and creates a temporary pair
    (20, 10)
  2. Then assigns: It puts
    20
    into
    a
    and
    10
    into
    b

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