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

Instruction

That's right! We can also modify a list by deleting some of its elements.

Deleting elements while iterating over a list is a bit tricky. Let's assume we have some erroneous values in our sleep_durations list (e.g., negative values) and we want to get rid of them. We may be tempted to write the following code:

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

What's wrong with this code? Let's find out!

Exercise

Run the template, which contains the code from the explanation.

As you can see, the code removed -590 from the list, but kept the value of -326. Why is that so?

The problem is that we iterate over the list and not over the indexes. Take a look at the diagram:

delete elements delete elements