Purify


#1



Could I get some help on this please.


def purify(number):
    for x in number:
        if x % 2 != 0:
            del x
        return number
n = [1, 2, 3, 4, 5]
print purify(n)
            


Replace this line with your code.


#2

x will contain read-only values, you can't delete those from the list

del and .remove() are both difficult approaches, go for the opposite approach, append even numbers to a new list

also, a function ends the moment a return keyword is reached, so your function ends in the first run of the loop. That can't be right, the whole loop needs to run to make sure the list is purified


#3

def purify(number):
    new_list = []
    for x in number:
        if x % 2 == 0:
            new_list.append(x)
    return number
n = [1, 2, 3, 4, 5]
print purify(n)

I'm doing something wrong


#4

yea, here:

return number

you return number, which is the original list, we need to return the purified list


#5

Ah right I'm appending to a new list. Cheers Stetim


#6

Yea, exactly. All sorted now and no more questions about purify?


#7

Thanks again but I have a few personal questions for you. How did you learn programming and know so much of it. Are you currently working on anything?


#9

def purify(numb):
for i in numb:
if (i%2!=0):
numb.remove(i)
return numb
#what is wrong with my code


#10

removing causes index shifts, lists can't have empty indexes, so after removing everything to the right of the removed number shifts one index to the left, causing succesive uneven numbers to be skipped

please follow this advise


#11

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