Trying to make a recursive program that removes a word from a list

def main():

    def remove(alist,word):
        if alist[0] == word:
            return remove(alist[1:],word)
        else:
            return [alist[0]] + remove(alist[1:],word)

    list1 = ['dog','cat','horse','dog','cat','horse']

    print(remove(list1,'dog'))

main()

This is my code. I'm not sure whats wrong with it. There is an error that says index out of range which I believe has to do with my third line but I'm not sure how to fix it.

Upvotes: 2

Views: 74

Answers (2)

Joshua Grigonis
Joshua Grigonis

Reputation: 768

Correct, this line:

if alist[0] == word:

Is trying to compare the first item in alist with word, but alist has no items.

Upvotes: 2

Eric Renouf
Eric Renouf

Reputation: 14510

I think your problem is that you never test if alist is empty. Since you keep removing the first element, eventually there won't be any elements left, and alist[0] will be an index out of range. If you just add

if not alist:
    return []

to the top of remove, I bet you'll be in good shape.

Upvotes: 6

Related Questions