Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Iterating over a list
Modifying lists
8. Swapping elements in Python
Working with multiple lists


Great! In Python, you can swap elements in a shorter and easier way – with only one line instead of three! The following part of the code:

temp_duration = sleep_durations[i]
sleep_durations[i] = sleep_durations[swap_index]
sleep_durations[swap_index] = temp_duration

can be replaced with:

sleep_durations[i], sleep_durations[swap_index] = sleep_durations[swap_index], sleep_durations[i]

This means: swap elements sleep_durations[i] and sleep_durations[swap_index].
Notice how there's no need to create a temporary variable!


Modify your code from the previous exercise. This time, use a new method – don't create a temporary variable.

Stuck? Here's a hint!

To swap elements x and y, you can use the following code:

x, y = y, x