Purify: Iteration skipping entries, need help


#1

Link: Purify

My code is:

def purify(list):
    ourlist = list
    for number in list:
        print number, number % 2
        if number % 2 == 1:
            ourlist.remove(number)
        print ourlist
            

print purify([1,2,3,9,7,5])

It displays

1 1
[2, 3, 9, 7, 5]
3 1
[2, 9, 7, 5]
7 1
[2, 9, 5]
None
None

So I'm wondering why when it's an odd number that gets deleted, it skips the next number on the list?

I changed "for numbers in ourlist" to "for numbers in list" hoping that it was just messing up the iteration through ourlist when it deleted an entry, but it still does it while iterating through list.
I'm lost...

Also I get:
"Oops, try again.
Your function crashed on [1] as input because your function throws a "'NoneType' object is not iterable" error."

Even though if I run the function with [1], it still works. (prints [])


#2

remove is a bad method to solve this problem, i explained the index shift here, i know this is lazy, but otherwise i would have to explain the index shift for the 4th time today.

Anyway, i suggest appending even numbers to a new list. Do ask if you have any questions


#3

Thanks. I was suspecting the "index shift" but didn't know what to call it! Helps a lot.

I was hoping it'd be a solution to have a different copy of the list, which the iteration was removing entries from... while iterating through a list that remained unchanged... could you please explain why that doesn't work?


#4

sounds fair, except this:

ourlist = list

doesn't make a copy of the list, otherwise it might actually work, lets see if it works:

ourlist = list(list)

list is a build in function, i wouldn't use it as variable, lets update the code:

def purify(lst):
    ourlist = list(lst)
    for number in lst:
        print number, number % 2
        if number % 2 == 1:
            ourlist.remove(number)
        print ourlist
            

print purify([1,2,3,9,7,5])

hm... stil not working, let me take a look

It is working, except for the list [1], hm... it seems to be working, except that SCT doesn't like it. Impressive, finding a working solution but which doesn't get accepted


#5

Found working solution!

def purify(ourlist):
    newlist = list(ourlist)
    for number in ourlist:
        if number % 2 == 1:
            newlist.remove(number)
    return newlist

Thanks for your help. Learned some potent new concepts this way.

Edit: Looks like the solution I found is exactly like yours, except the debugging lines. Interesting.