Skip to main content

Section 9.17 Deleting Negative Elements: The Rewrite

Back in Subsection 9.12.1, we wrote 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 did not return a new list; it modified the list we give it “in place”. The function was a modifier, and it had the side effect of changing the list passed to it.
Now, we will rewrite the function so that it returns a new list with the non-negative elements, leaving the original argument untouched. Because we aren’t touching our original list by removing entries from it, we can go back to our original plan, slightly modified:
  1. Set the result list to the empty list
  2. Use a for loop that counts from 0 to the list length (minus one).
  3. If the entry at a given index is not negative, append that element to the result list.
  4. When the loop is complete, return the result list.

Subsection 9.17.1 Advanced Topic: When to Update a List

Sharp-eyed readers might have seen the use of append in line eight and are wondering if that violates our “don’t update a list in place” rule. Yes and no.
While we are updating a list in place, it’s not the original list that the user gave us. That list remains untouched throughout the program. Perhaps it is better to restate the rule as “when a list is passed as a parameter, don’t update it in place; instead, return a new list to the caller”.
So, for example, if you wanted a function that sorts a list without changing the parameter, you could write something like this: