Lesson 05-09: Building List Functions: removeall

Learning Target: I can create a python function that will remove all elements of a given value.

Assignment

In the area below, create a method called removeAll() that will take in two arguments:

  • original - the original list
  • del_value - the value you want to replace in the list

and will remove ALL elements that in original that match del_value. The function should modify the value of original.

Example:

removeAll([1,2,1,2,3,1,2],1) should return [2,2,3,2]

Hints

This time, you’re probably going to want a loop, but be careful! Remember that when you remove an element, it shifts the index of all the remaining elements down by 1!
You’ll probably want to use a while loop here. Also consider: In a while loop, you’re likely going to have a variable that keeps track of the index. When do you want the index to move up? Conversely, when do you want the index to not change?

Here’s one way to do it:

def removeAll(original,del_value):
    index = 0

    while(index < len(original)):
        if original[index] == del_value:
            original.remove(del_value)
        else:
            index = index + 1

Here’s another way where we use for loops to count the occurrences of del_value, then another for loop do delete all of them at once.

def removeAll(original,del_value):
    count = 0
    for e in original:
        if e == del_value:
            count = count + 1

    for x in range(count):
        original.remove(del_value)
Next Section - Lesson 05-10: Strings to Lists