Purify?


#1



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


If there are two or more odd numbers in a row, it only removes one of the numbers.
Oops, try again.
Your function fails on purify([4, 5, 5, 4]).
It returns [4, 5, 4] when it should return [4, 4].


def purify(numbers):
    for x in numbers:
        if x % 2 == 1:
            numbers.remove(x)
    return numbers        
print purify([4, 1, 3, 4])


#2

yep, because you are removing from the same list as your are looping over index shifts occurs

lists can't have empty indexes, so the moment you removing something from the list everything to the right of where you removed, shifts one index to the left, then your loop progresses to the next index, causing a second odd number to be skipped

the opposite approach is better, append even numbers to a new list


#3

thanks! that was the fix


#4

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