Purify section



I know appending the even numbers in the list to a new list would work but I just want to find out why this method does not work. The code only removes a few odd numbers instead of all. What is the reason behind this occurrence? Thanks in advance for any help!

Replace this line with your code. 
def purify(dirtylist):
    dl = dirtylist[:] ##create a new list so not to modify the original list 
    for number in dl:
        if number % 2 != 0:
            print dl ##see the process 
    return dl    
#just my own testing
testlist = [4,5,5,5,5,5,5,5,5]
print purify(testlist)
print testlist ##test whether the original list is still there


index skipping, lets say we have this simple list:


agree with me that the items are indexed at: 0,1,2,3? Right, so now the loop is going to run, at index 0 nothing has to happen, the number is even.

at index 1, we encounter a 5 so we have to remove it. But now we get into trouble, because we remove the 5 from index 1, but this empty position has to be filled. So the 5 from index 2 will go to index 1, but the loop continues to index 2, which now holds 4.

short version: index shift causes the problem

Can you solve it? Yes, but that would increase the complexity to something like this:

def purify(ls):
        for i in range(len(ls)):
            if ls[i]%2!=0:
                while ls[i] % 2 != 0:
        return ls
    except IndexError:
        return ls
print purify([4,5,5,4])

why does this work? In the for loop, i build a while loop to catch any consecutive odd numbers, but this mean the for loop will run out of indexes, so you have to catch that with try and except


sorry for the late reply because I just read your post. thank you for the clear explanation :slight_smile: