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!