12/15 L.remove removes one, but L.append appends all


#1

https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/purify?action=lesson_resume

Can someone tell me why this code doesn’t work?
It only removes the first instance of the unwanted number, rather than each one, meaning if the list contains multiple instances of a number, it doesn’t remove each one in the ‘for’ loop

[spoiler]def purify(even_it):
    even = even_it
    for number in even:
        if number % 2 == 1:
            even.remove(number)
    return even[/spoiler]

but the opposite method works perfectly

[spoiler]def purify(even_it):
    even = []
    for number in even_it:
        if number % 2 == 0:
            even.append(number)
    return even[/spoiler]


#2

this is not true, this:

def purify(even_it):
    even = even_it
    for number in even:
        if number % 2 == 1:
            even.remove(number)
    return even

print purify([5,4,5])

is working fine.

also, this:

even = even_it

will not make a copy of the list, just another variable referencing to the same list in memory.

the problem is index shift, if we have successive odd/uneven numbers, we have a problem.

lists can’t have empty indexes, when we remove something, everything to the right of the removed item shifts one index to the left, then the loop goes to the next index, causing a skip.


#3

This is what was causing my problem then.
One of my lists was [4, 5, 5, 4]
Is there a way to ensure the shift doesn’t interfere with the for loop?


#4

one list is quite a difference from all lists:

index shift is only problem when removing from the same list as you are looping over, so is there a way around it? There must be, but the fact that you run into problems, is a signal this option might not be worth exploring


#5

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