Purify section


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/2?curriculum_id=4f89dab3d788890003000096

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:
            dl.remove(number)
            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


#2

index skipping, lets say we have this simple list:

[4,5,5,4]

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):
    try:
        for i in range(len(ls)):
            if ls[i]%2!=0:
                while ls[i] % 2 != 0:
                    del(ls[i])
        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


#3

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