Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Recap
Iterating over a list
Modifying lists
10. Deleting list elements – part 2
Working with multiple lists
Congratulations

Instruction

Okay. You could see that the method we wrote didn't work. How can we correctly remove all negative numbers from the list? The secret is to create a copy of the list. Take a look:

sleep_durations = [268, -590, -326, 506]
for duration in sleep_durations[:]:
  if duration < 0:
    sleep_durations.remove(duration)
print(sleep_durations)

Instead of iterating over sleep_durations, we created a temporary copy using sleep_durations[:]. The syntax [:] means "copy all elements from the list". When we use this, we iterate over a copy containing all the list elements in each iteration, but we remove items from the actual list. This gives us the correct algorithm.

Exercise

As you can see, some erroneous data was inserted into Martha's monthly spending list. Remove all values less than 100 from monthly_spendings and then print the monthly_spendings list.

Stuck? Here's a hint!

Create a copy of the list using monthly_spendings[:].