Awesome! Now let's practice filtering a list.https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/2?curriculum_id=4f89dab3d788890003000096#

This is the message"Oops, try again. Your function fails on purify([4, 5, 5, 4]). It returns [4, 5, 4] when it should return [4, 4]."

I just wonder why this happens. Why can't delete the second '5'?

def purify(x):
    for i in x:
        if i % 2 != 0:
    return x


removing from the same list you are looping over causes index shifts, causing problems


so, I can't modify the same list I'm looping?


well, you can, but then index shifts occur which causes successive odd numbers to not be properly removed. You either need to solve this problem, or choice a different approach (appending even numbers to a new list)


ok, I get it. Thanks a lot!


after removing item using remove() function changes the index of all items. so recursion can be used like this:
(it works)

def purify(items):
     for item in items:
          if item % 2 != 0:
     return items;


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