count items in generator

Paul Rubin http
Sun May 14 01:50:06 EDT 2006


"George Sakkis" <george.sakkis at gmail.com> writes:
> As clunky as it seems, I don't think you can beat it in terms of
> brevity; if you care about memory efficiency though, here's what I use:
> 
> def length(iterable):
>     try: return len(iterable)
>     except:
>         i = 0
>         for x in iterable: i += 1
>         return i

Alex's example amounted to something like that, for the generator
case.  Notice that the argument to sum() was a generator
comprehension.  The sum function then iterated through it.



More information about the Python-list mailing list