Why my alternative solution did not work?


#1
def purify(l):
    for i in l:
        if i % 2 != 0:
            l.remove(i)
    return l

when I input [4,5,5,4] it returns

[4,5,4]

why is it so? the function should iterate through all elements of thee given list and remove the element that is not a even number.


#2

Yes, but what if you remove an item? Lets say we have:

4   5   5   4
0   1   2   3

the top row is the lists, the bottom one are the indexes.

the moment we remove the 5 from index 1, the list can’t have an empty spot, so everything to the right of the removed elements moves one spot to the left:

4   5   4
0   1   2

good, with the remove() completed, the loop can continue to the next index (which is 2)

so it will skip items because of this index shift that occurs when you remove an item.


#3

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