capypad
0 day streak
python / beginner
Snippet

Swapping Two Variables

Python allows you to swap the values of two variables in a single line without using a temporary third variable. This is called tuple unpacking.

snippet.py
python
1
2
3
a = 5
b = 10
a, b = b, a
Breakdown
1
a = 5
Initialize variable 'a' with the value 5.
2
b = 10
Initialize variable 'b' with the value 10.
3
a, b = b, a
Simultaneously assign the value of 'b' to 'a' and the value of 'a' to 'b'.