Purify


#1

I have 3 solutions for this task.
Can anyone tell me what's the problem with second solution?

First (works):

def purify(x):
    y = []
    for i in x:
        if i % 2 == 0:
            y += [i]
    return y

Second (doesn't work)

def purify(x):
    for i in x:
        if i % 2 != 0:
            x.remove(i)
    return x

Third (works):

def purify(x):
    y = []
    for i in x:
        if i % 2 == 0:
            y.append(i)
    return y

#2

That's odd, here, I ran your second function off a list I created and it worked just fine. Try it out yourself, perhaps something else was interfering with your output..

n=[1,2,3,4,5]

def purify(x):
    for i in x:
        if i % 2 != 0:
            x.remove(i)
    print x
    
purify(n)

#3

try n = [1, 1, 1, 1, 1, 2, 3, 4, 5] and you'll see


#5

The problem with recurrent integers is that if your loop hasn't specified the exact range, then it misses the recurrent integers. You can solve this by simply being more specific about the range you wish to iterate over...so instead of simply using the loop 'for i in x', you use 'for i in x[0:] which tells python to look through the list from the first ([0]) index till the last.

Here's the code for the same...hope this helps...

n = [1, 1, 1, 1, 1, 2, 3, 4, 5] 

def purify(x):
    for i in x[0:]: #instead of 'for i in x'
        if i%2!=0:
            x.remove(i)
    print x #should print '2, 4'
    
purify(n)

#7

Finally a use of .remove() that doesn't throw a fit. Nice one.