count items in generator

Alex Martelli aleax at mac.com
Sun May 14 12:30:37 EDT 2006


Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:

> "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.

True.  Changing the except clause here to

except: return sum(1 for x in iterable)

keeps George's optimization (O(1), not O(N), for containers) and is a
bit faster (while still O(N)) for non-container iterables.


Alex



More information about the Python-list mailing list