Purify


#1



hello~ It's my first time to write something on this board.
As you can see the my code, i tried it using little bit different way.
But when it's run with [4 , 5, 5, 4].
it's only remove third index value and i don't know why it's happening.

Plz tell me why and explain how do i can fix this.
Thank you so much.


 
def purify(list_of_numbers):
    for x in list_of_numbers:
        print x
        if x % 2 != 0:
            list_of_numbers.remove(x)
    return list_of_numbers
    
print purify([4, 5, 5, 4])


#2

you are removing from the same list as you are looping over, this means that if we have successive odd numbers, index shift occurs, which causes the second successive odd number not to be removed


#3

Thank you for answering.

I figured out how to fix it.
if you change like this -> for x in list_of_numbers[:]:
it will work. But, someone said it's not good for performance.


#4

using list slicing you make a copy of the list, given you do this in the for loop, i would say this happens every iteration.

If you really want to do this, make a copy of the list beforehand


#5

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