Purify -- do it in reverse


Hi there, I understand how the purify code could work if I do append way of finding even number, but I do not understand why my deleting odd number way gives the error message of saying index out of range?

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

Thank you!

Replace this line with your code.


well, lets say we have this list:


the numbers 1, 3 and 5 should get removed. However, doing this would mean the loop which needs to get to index 4 (as determined by range) will no longer exist, given only 2 and 4 (index 0 and index 1) will be in the list

list can't have empty indexes, so the moment you remove something from the list, everything to the right of the removed item shift one index to the left

this also poses our next problem, if there are successive uneven/odd numbers, we have a problem (due to the index shift i explained in the previous paragraph)

don't get me wrong, removing is not an impossible solution, but its trickier then appending even numbers to a new list


I see, great point. thank you


we can actually show this:

def purify(x):
    for i in range(len(x)):
        print i, x
        if x[i] % 2 != 0:
    return x

so i is the index, as you can see, it attempt to access the value at index 3, which no longer exist, given you removed something from the list

furthermore you can beautiful see the index shift here:

1 [4, 5, 5, 4]
2 [4, 5, 4]

when the loop is at index 2, which now contains 4 you can see it skips the 5

Hope this gives you the insight you where looking for.


yes indeed, great! absolutely. And how do you manage to print out each iteration please?


well, first i add a function call. Given a function won't execute unless called

then i simply added a print statement in the loop.

I included the code in my previous reply. Its yours, except for the function call and print statement i added, you can study the code :slight_smile:


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