Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a list [duplicate]

Tags:

python

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

like image 948
user2679806 Avatar asked Aug 13 '13 18:08

user2679806


2 Answers

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]
like image 52
NPE Avatar answered Sep 24 '22 01:09

NPE


One option I didn't see mentioned was, ironically filter:

>>> filter(lambda x: not x % 2, [4,5,5,4])
[4, 4]
like image 21
Burhan Khalid Avatar answered Sep 22 '22 01:09

Burhan Khalid