Purify : my code wont remove 5 from list?



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

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


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

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.


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


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


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