# Purify

#1

purify
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:
x.remove(i)
return x``````

#2

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

#3

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

#4

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)

#5

ok, I get it. Thanks a lot!

#6

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:
items.remove(item);
purify(items);
return items;``````

#7

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