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

Chris Angelico rosuav at gmail.com
Fri Oct 3 17:17:25 CEST 2014


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


More information about the Python-ideas mailing list