Lesson 05-08: Building List Functions: replaceAll

Learning Target: I can create a python function that will replace a given element in a list with another given element.

Assignment

In the area below, create a function called replaceAll() that will take in three arguments:

  • original - the original list
  • find_value - the value you want to replace in the list
  • replace_with - the value you want to replace it with in the list

and will replace ALL elements that in original that match find_value and replace their value with that of replace_with. This function should modify the value of original.

You may only use the following list methods: append(), insert(), remove(), len().

Example:

replace([1,2,1,2],1,"a") should return ["a",2,"a",2]

Hints

It’s kinda like copying a list, except you want to change some of the values. You’ll need a conditional somewhere... how do you know whether you should be changing the value or not?
How do you check if the list element you’re looking at matches the list element you want to replace? How do you actually replace it? You’ll need to use a for loop that loops through the indexes of the list, since you want to alter values (using a for-each loop doesn’t let you alter values).

Here’s one way to do it:

def replace(original,find_value,replace_with):
    for index in range(len(original)):
        if original[index] == find_value:
            original[index] = replace_with
Next Section - Lesson 05-09: Building List Functions: removeall