Swapping Variable Values in Python

Lesson 11. Swapping Variable Values in Python
In Python, you can swap the values of two variables in a single line without using a temporary variable.
Example: Swapping Two Variables
a = 5
b = 10
# Swap values
a, b = b, a
print(a) # Output: 10
print(b) # Output: 5
💡 How It Works:
- On the right side →
(b, a)
creates a tuple(10, 5)
. - On the left side → Python unpacks that tuple into
a
andb
.
After the operation:
a
becomes10
b
becomes5
🌍 Real-Life Analogy
Imagine you and a friend are holding two cups — one with coffee and one with tea.
Instead of pouring both into a third cup (the “temporary variable”)
, you simply hand each other your cups. That’s what Python does when swapping — it just exchanges the values directly.
🧩 Try It Yourself Try swapping other variable types — for example, strings or floats: ```python x = “Apple” y = “Banana”
x, y = y, x
print(x) # Output: Banana print(y) # Output: Apple
Swap more than two variables:
```python
a, b, c = 1, 2, 3
a, b, c = c, a, b
print(a, b, c) # Output: 3 1 2
Now that you understand Python variables, your next step is to learn about Assigning Values from Collections (Unpacking) in detail.