altering an object as you iterate over it?

Bruno Desthuilliers bdesth.quelquechose at
Sat May 20 05:00:54 CEST 2006

bruno at modulix a écrit :

(responding to myself)
(but under another identity - now that's a bit schizophrenic, isn't it ?-)

> For the general case, the best way to go would probably be an iterator:
> def iterfilter(fileObj):
>   for line in fileObj:
>     if line.strip():
>       yield line
> f = open(path, 'r')
> for line in iterfilter(f):
>   doSomethingWith(line)

Which is good as an example of simple iterator, but pretty useless since 
we have itertools :

import itertools
f = open(path, 'r')
for line in itertools.ifilter(lambda l: l.strip(), f):

More information about the Python-list mailing list