<div dir="ltr">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.<div><br></div><div>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:</div><div>valid_customers = len(customer for customer in customers if customer.is_valid())</div><div><br></div><div>that would be useful.</div></div><div class="gmail_extra"><br><div class="gmail_quote">On Fri, Oct 3, 2014 at 5:17 PM, Chris Angelico <span dir="ltr"><<a href="mailto:rosuav@gmail.com" target="_blank">rosuav@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div class="HOEnZb"><div class="h5">On Sat, Oct 4, 2014 at 1:09 AM, Thomas Chaumeny <<a href="mailto:t.chaumeny@gmail.com">t.chaumeny@gmail.com</a>> wrote:<br>
> I have just come across some code counting a generator comprehension<br>
> expression by doing len([foo for foo in bar if some_condition]) and I<br>
> realized it might be better if we could just use len(foo for foo in bar if<br>
> some_condition) as it would avoid a list allocation in memory.<br>
><br>
> Another possibility is to write sum(1 for foo in bar if some_condition), but<br>
> that is not optimal either as it generates a lot of intermediate additions<br>
> which should not be needed.<br>
><br>
> Sure, len(generator) might lead to an infinite loop but since sum(generator)<br>
> is allowed in Python I see no reason why len(generator) isn't.<br>
<br>
</div></div>I think len() would be confusing, as it has to exhaust the generator<br>
to find out the length. The easiest would be to roll your own:<br>
<br>
def genlen(gen):<br>
    len = 0<br>
    for len, _ in enumerate(gen, 1): pass<br>
    return len<br>
<br>
At least then it's clear that it'll iterate over it completely.<br>
<br>
ChrisA<br>
_______________________________________________<br>
<div class="HOEnZb"><div class="h5">Python-ideas mailing list<br>
<a href="mailto:Python-ideas@python.org">Python-ideas@python.org</a><br>
<a href="https://mail.python.org/mailman/listinfo/python-ideas" target="_blank">https://mail.python.org/mailman/listinfo/python-ideas</a><br>
Code of Conduct: <a href="http://python.org/psf/codeofconduct/" target="_blank">http://python.org/psf/codeofconduct/</a><br>
</div></div></blockquote></div><br></div>