Removal of element from list while traversing causes the next element to be skipped

cokofreedom at gmail.com cokofreedom at gmail.com
Wed Jan 30 10:06:38 CET 2008


On Jan 30, 9:50 am, Santiago  Romero <srom... at gmail.com> wrote:
> On 30 ene, 08:09, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
>
> > Santiago  Romero <srom... at gmail.com> writes:
>
> > > > >>> li = [1,2,3,4,5]
> > > > >>> filter(lambda x: x != 3, li)
> > > > [1, 2, 4, 5]
>
> > >  I haven't measured it, but this should be the fast solution in all
> > > the thread ...
>
> > li.remove(3) is probably faster.
>
>  But that only removes the first ocurrence of item==3.
>
>  In  a = [1, 2, 3, 3, 3, 4, 3, 3, 2, 3], the filter solution will
> efectively remove all items with value == 3 while li.remove(3) will
> only remove the first ocurrence.
>
>  Bye!

from itertools import ifilter
print [x for x in ifilter(lambda x: x != 99, li)]

Will this one be faster or slower than filter?



More information about the Python-list mailing list