trouble with a find and replace function within a list

The problem with your code is that it is using a while loop and it is also recursive. Inside the while loop the function gets called again with the same exact parameters, generating an useless loop. Also, the functions stops when it gets to the first “return” statement, so the return orig statement will never get executed.

A better way to approach this is using a for loop:

def findAndReplace(orig, toFind, replacement):
    for i, element in enumerate(orig):
        if element == toFind:
            orig[i] = replacement
    return orig

Using the for loop with the enumerate function, you are able to get each element of the list and its index. This function iterates through the whole list, checks if the element it is currently on is the one to replace, and if so, replaces it. By doing so, every element of the list that matches with the toFind parameter will get replaced. Be sure not to use this function on strings though, you will get an error because they are immutable!

Another way to approach this is using list comprehension:

def findAndReplace(orig, toFind, replacement):
    return [replacement if element == toFind else element for element in orig]

In any of these cases, the function returns a new list with the replaced value, so an example of using this function looks like this:

a = ["pizza", "pasta", "replaceme"]
a = findAndReplace(a, "replaceme", "spaghetti")

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top