Purify help


#1



So I'm having trouble understanding why this code that I've written doesn't work. By my understanding, this should do the job.


This is the error that I keep getting when I run the code:

Oops, try again. Your function crashed on [1] as input because your function throws a "list assignment index out of range" error.


Any suggestions with what I have?


def purify(lst):
    for item in lst:
        if item % 2 != 0:
            del(lst[item])
    return lst


#2

If you get index-out-of-range you'll want to look at what you're using as index.

Also, deleting from a list that you are currently iterating through might not be a very good idea, as that will cause elements to move which will affect the iterating. Your loop would need to change its behaviour to compensate for the moving elements. Is there an alternative to removing?


#3

Gotcha, yeah I didn't think that deleting would mess up the iterating. I'll just add to a new list the items that are even.

Thanks @ionatan


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.