Purify -- do it in reverse


#1



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:
            del(x[i])
   return x

Thank you!


Replace this line with your code.


#2

well, lets say we have this list:

[1,2,3,4,5])

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


#3

I see, great point. thank you


#4

we can actually show this:

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

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.


#5

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


#6

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:


#7

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