Purify : my code wont remove 5 from list?


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/2?

The code below removes all odd numbers except 5 why??????


def purify(l):
    for x in l:
        if x % 2 != 0:
            l.remove(x)
    return l
    
print purify([2,3,2,3,5,12,3,])


#2

There are two ways you can approach this problem. You can either strip the odds away (which seems to be your approach) or add the evens to another list and return the result. Personally I chose to add the evens to a new list.

I would create a list called result.
result = []

I would change the if condition to ==
if x % 2 == 0:

I would then add x to the new list
result.append(x)

Finally return it
return result

Sometimes programs have issues modifying and original list. That is why I prefer to work with a new identical copy.


#3

Thanks for the answer but I was just wondering why it removed every odd number except 5.


#4

Like I said it is probably having an issue modifying the list that you are putting in.


#5

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