I cannot fix this one


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/2?curriculum_id=4f89dab3d788890003000096#


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


#2

here:

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


#3

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


#4

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


#5

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

#6

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


#7

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