[Python-ideas] Make len() usable on a generator

Thomas Chaumeny t.chaumeny at gmail.com
Fri Oct 3 17:21:49 CEST 2014


Yes, it has to exhaust the generator to find the length, but that also is
what list(generator) or sum(generator) have to do and yet they are allowed
constructions.

Actually I don't think that calling len(generator) would be very useful
with a generator variable, but with an "anonymous" generator using a
comprehension like:
valid_customers = len(customer for customer in customers if
customer.is_valid())

that would be useful.

On Fri, Oct 3, 2014 at 5:17 PM, Chris Angelico <rosuav at gmail.com> wrote:

> On Sat, Oct 4, 2014 at 1:09 AM, Thomas Chaumeny <t.chaumeny at gmail.com>
> wrote:
> > I have just come across some code counting a generator comprehension
> > expression by doing len([foo for foo in bar if some_condition]) and I
> > realized it might be better if we could just use len(foo for foo in bar
> if
> > some_condition) as it would avoid a list allocation in memory.
> >
> > Another possibility is to write sum(1 for foo in bar if some_condition),
> but
> > that is not optimal either as it generates a lot of intermediate
> additions
> > which should not be needed.
> >
> > Sure, len(generator) might lead to an infinite loop but since
> sum(generator)
> > is allowed in Python I see no reason why len(generator) isn't.
>
> I think len() would be confusing, as it has to exhaust the generator
> to find out the length. The easiest would be to roll your own:
>
> def genlen(gen):
>     len = 0
>     for len, _ in enumerate(gen, 1): pass
>     return len
>
> At least then it's clear that it'll iterate over it completely.
>
> ChrisA
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141003/7d556f5f/attachment.html>


More information about the Python-ideas mailing list