0

I'm given a practice to write a function in Python that takes a list as input which includes all integers . I should remove all odd numbers and let even numbers stay and return the list .

This is my function :

def purify (lst):
    for key in lst:
        if key % 2:
            lst.remove(key)
return lst

When I run it these are the results I get : (here are some test cases)

print purify([1,2,3,4,5,6,7,8,9])

results :

1 3 5 7 9 [2,4,6,8]

Another test case : When I run using this line :

print purify ([4,5,5,4,5,5])

results :

4 5 4 5 [4,4,5,5]

I'm not sure what's happening , if I remove that "if" condition , then there is no problem (like this):

def purify (lst):
    for key in lst:
        print key
return lst

It prints all values in list and doesn't skip any

Am I doing something wrong?

Ardeshir Izadi
  • 955
  • 1
  • 7
  • 25

1 Answers1

0

The operator % returns an integer value not a boolean, so when the return value is 0 it skips the statement. Also you are modifiying the list you are iterating over, not good...

Try this:

def purify (lst):
    retLst = []
    for key in lst:
        if key % 2 == 0:
            lst.append(key)
    return retLst

Should work.

Netwave
  • 40,134
  • 6
  • 50
  • 93
  • 2
    Errr.... But a non-zero value is a boolean True, and a zero (0) is a boolean False.... – Jon Clements Jan 04 '14 at 19:03
  • 2
    The boolean values True and False can be replaced with 1 and 0 respectively, meaning if True is the same as if 1 – Ffisegydd Jan 04 '14 at 19:03
  • I am no Python programmer yet, but I'm pretty sure the solution is to make a copy of 'lst' BEFORE the for loop (and not just reference-copy) – Davs Jan 04 '14 at 19:45
  • Thanks ! I know the solution , BUT there is still something I can't understand ! "When the return value is 0 it skips the statement" and it becomes Zero IF AND ONLY IF the the list value is even (and odd) and that's exactly what I want . BUT my problem is it skips odd values too (although my if doesn't return 0) (it doesn't go over some odd values at all) – Ardeshir Izadi Jan 05 '14 at 09:06
  • @ArdeshirIzadi, it is having strange behaviour becouse you are modifiying the list you are iterating over so you cant have knowlege about what the interpreter will do to deal with it, thats why I suggest creating another list and appending the correct values to it for return it later. It dosnt provide worst performance (not too much in this case) to create one more list. – Netwave Jan 05 '14 at 10:44