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

Thomas Chaumeny t.chaumeny at gmail.com
Fri Oct 3 17:09:20 CEST 2014


Hi!

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.

What do you think ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141003/9ac61029/attachment.html>


More information about the Python-ideas mailing list