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

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


In that case it works because boolean values will be converted to 0/1 but
you have to force the construction to generate booleans. Also, that
generates intermediate additions at each step which might make it slower
than a fast iteration until exhaustion.

On Fri, Oct 3, 2014 at 5:40 PM, Todd <toddrjen at gmail.com> wrote:

>
> On Oct 3, 2014 5:22 PM, "Thomas Chaumeny" <t.chaumeny at gmail.com> wrote:
> >
> > 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.
>
> You could just do:
> sum(customer.is_valid() for customer in customers)
>
> _______________________________________________
> 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/6242cfb6/attachment.html>


More information about the Python-ideas mailing list