0

I was trying a simple list filtering by removing those elements in a list that meet a condition.

 >>> a = ["a" , "e" , "i" , "o" , "u"]
 >>> for elem in a:
 ...     a.remove(elem)

In this case, I am not filtering, I am trying remove all elements. However, If I print a this is what I see:

>>> print a
["e" , "o"]

It not possible remove all elements in array by this way. Python removes the element, reassign the index and then increment it. So, Python skips an element in each iteration. If it doesn't works for the simplest case, how could I properly implement a list filtering?

>>> numbers = [100 , 102 , 103 , 105 , 107, 108, 110, 120]
>>> for elem in numbers:
...     if elem % 2 == 0:
...         numbers.remove(elem)
... 
>>> numbers
[102, 103, 105, 107, 110]

In this case, the more natural (in my opinion ) implementation of the list filtering doesn't work... how do you control this kind of operations??

Thanks!

Luis González
  • 3,199
  • 26
  • 43
  • 2
    For an illustration of why removing elements form a sequence you are currently iterating over is bad see my answer [here](http://stackoverflow.com/a/31704332/1318181) – kylieCatt Dec 18 '15 at 08:35

1 Answers1

-4

Just use the built-in function filter():

>>> filter(lambda x: x % 2, numbers)
[103, 105, 107]
kylieCatt
  • 10,672
  • 5
  • 43
  • 51
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 7
    `filter` returns a generator object in Python 3, and in Python 2, this still creates *a new* list without modifying the original list. Also, your answer is lacking information, being mostly a link-only answer which is highly discouraged. Judging by your reputation count, you really should know better. – poke Dec 18 '15 at 08:24
  • @poke: Python 3 is less commonly used than Python 2, so I don't really mind too much if the minority of users need to wrap the result in an extra `list()` call. As for link-only, it did take me an extra minute to add a full example. – John Zwinck Dec 18 '15 at 08:27