Lesson 05-09: Building List Functions: removeall

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


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.


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


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:
            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):
Next Section - Lesson 05-10: Strings to Lists