Skip to main content

Section 9.10 Programming Phase 1: Planning

Let’s write a function that deletes all the negative elements in a list; if you give it the list [10, -66, -47, 11, 505, -217], the list will be modified to [10, 11, 505]. This function will not return a new list; it will modify the list we give it “in place”.
Here’s the plan: use a for loop that counts from 0 to the list length minus one. If the entry at a given index is negative, we delete the element using del. Sounds like a plan. Let’s see it in action:
Well. That didn’t work. Why did we end up with IndexError: list index out of range? Before you try fixing the problem, please read the next page.