I cannot fix this one



Your function fails on purify([1]). It returns [1] when it should return []

it should return the required answer

def purify(numbers):
    for i in range(1,len(numbers)):
        if numbers[i-1]%2!=0:
            del numbers[i-1]
    return numbers



for i in range(1,len(numbers)):

why start at one? list indexes start at zero

using del is a difficult approach, appending even numbers to new list is easier


But if i keep it as range(0,len(numbers)), then also it does not give the desired output.


can i see an updated version of your code? Please go for the opposite approach, appending even numbers to a new list


i would definitely go for that approach but i want to know whats wrong with my code!

hence my code:
def purify(numbers):

for i in range(0,len(numbers)):
    if numbers[i]%2!=0:
        del numbers[i]
return numbers


once you remove items, list can't have empty indexes, so everything to the left of the removed item shifts to the right, which inevitable causes your loop to get an index error


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