Swap Two Variables
Beginner · Write the code · from Python Unpacking: Starred Expressions, Swapping, and Destructuring
From the lesson: Python Unpacking: Starred Expressions, Swapping, and Destructuring
Imagine you order a package online that contains three items: a book, headphones, and a phone case. When the box arrives, you open it and put each item where it belongs. The book goes on the shelf, headphones go on the desk, and the case goes on your phone.
Read the lessonThe variables first and second have the wrong values. Swap them using Python's unpacking syntax (one line, no temporary variable), then print both.
first = 'goodbye'
second = 'hello'
# Swap first and second in one line
print(first)
print(second)
More Unpacking exercises
- Unpack a CoordinateBeginner
- Head and Tail with StarIntermediate
- Predict the Unpacking OutputIntermediate
- Unpack Student RecordsAdvanced
All Python exercises · 50 practice problems · Data Structures quiz