Purify: 12/15


#1



Purify

Oops, try again. Your function fails on purify([1]). It returns [2, 4, 6, 8] when it should return [].

Please someone help me resolve the error

numbers=[1]
new_numbers=[]
def purify(numbers):
    for i in numbers:
        if i%2==0:
            new_numbers.append(i)
        else:
            numbers.remove(i)
    return new_numbers
print purify(numbers)

Output:
[]
None


#3

A word of caution. Do not perform an mutable operation on a list while iterating through it. You are calling remove on the list. If I understand right, the purify function is to only retain the even numbers. If that is the case, you do not need the else condition. The if condition is sufficient. It will handle the empty use-case as well since it would not enter the for loop and the new_number variable is already initialised to []


#4

You do not need to check for an empty condition explicitly as the for loop body would not be executed if the list is empty. Also your else condition body is incorrect. You have given a comparison operation. Even if it was an assignment operation, the solution is still incorrect as you would be resetting the output each time there is an odd number in the list.


#5

def purify(L):
result = [ x for x in L if x % 2 == 0]
return result