Im writing a simple function to take out any odd numbers from a list and return a list of only the even ones.
def purify(numbers):
for i in numbers:
if i%2!=0:
numbers.remove(i)
return numbers
print purify([4,5,5,4])
when applied above
it returns: [4, 5, 4] why doesnt the second 5 get removed as it also justifys the if?
Im looking less for a different method to the problem and more to understand why this happens.
thanks and sorry if this is stupid q.. Joe
When you remove an item, the items that follow get moved one position to the left. This results in the loop skipping some items.
BTW, a more idiomatic way to write that code is
numbers = [num for num in numbers if num % 2 == 0]
One option I didn't see mentioned was, ironically filter
:
>>> filter(lambda x: not x % 2, [4,5,5,4])
[4, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With