Alternative to standard C "for"

Michael Spencer mahs at telcopartners.com
Thu Feb 17 14:04:31 EST 2005


James Stroud wrote:

> 
> 
> It seems I need constructs like this all of the time
> 
> i = 0
> while i < len(somelist):
>   if oughta_pop_it(somelist[i]):
>     somelist.pop(i)
>   else:
>     i += 1
> 
> There has to be a better way...
> 
Do you have to modify your list in place?

If not, just create a copy with the filtered items:

somelist = [item for item in somelist if not oughta_pop_it(item)]

or you could use filter or itertools.ifilter to do much the same thing

Michael






More information about the Python-list mailing list