Purify


#1



Hey guys,
I don't get what's wrong with this code. The error: "Oops, try again. Your function fails on purify([4, 5, 5, 4]). It returns [4, 5, 4] when it should return [4, 4]."
Why should it remove one "5" from the list but not the other? I hope you can help me with this problem. ^^


def purify(numbers):
    for n in numbers:
        if n % 2 != 0:
            numbers.remove(n)
    return numbers


#2

It shouldn't remove just one.


#3

The only way we can mutate a list we are iterating is if we start from the right hand side and work backwards through the list. Consider the following:

def purify(numbers):
    for n in range(len(numbers), 0, -1):
        if numbers[n-1] % 2 != 0:
            numbers.remove(numbers[n-1])
    return numbers
 > purify([7,4,5,5,4])
=> [4, 4]

We can also use del() in much the same way...

def purify(numbers):
    for n in range(len(numbers), 0, -1):
        if numbers[n-1] % 2 != 0:
            del(numbers[n-1])
    return numbers

The main point is that we are moving from right to left in the list. If an element is removed, the element that slots into that position is one which has already been examined. We are not shifting elements that we haven't seen yet.


#4

thanks a lot, I finally got it :grin:


#6