[Python-ideas] iterator length

Alexandru Moșoi brtzsnr at gmail.com
Mon Aug 9 22:17:23 CEST 2010


2010/8/9 Paul Moore <p.f.moore at gmail.com>:
> If you could show some real code that uses your ilen function, that
> would help clarify. But it still won't explain why the function should
> be built in rather than just defined by your code where it's needed -
> you'll have to have some very common and compelling use cases to argue
> that.

My requirements was to count the non-zero elements from a list like this:
   sum(1 for e in iterator if not e)

What I'm really looking for is the number of elements in a list comprehension:
   len(list(for e in iterator if not e))

but this is not generally useful nor optimal in terms of memory requirements.

My idea was to implement the above with the aid of itertools.ifilter:
   ilen(itertools.ifilter(pred, iterable))

if pred is None, this would translate in my usecase.

Since I first post this I learned that ilen (or something similar) was
rejected before due to similar concerns: it consumes the iterator,
it's not a real optimization.

How about: count(pred, iterable) which returns the same value as
len(filter(pred, iterable))?


-- 
Alexandru Moșoi
http://www.alexandru.mosoi.ro/



More information about the Python-ideas mailing list