count items in generator

George Sakkis george.sakkis at gmail.com
Sun May 14 22:09:24 EDT 2006


Delaney, Timothy (Tim) wrote:

> George Sakkis wrote:
>
> > Paul Rubin wrote:
> >
> >> claird at lairds.us (Cameron Laird) writes:
> >>> For that matter, would it be an advantage for len() to operate
> >>> on iterables?
> >>
> >>    print len(itertools.count())
> >>
> >> Ouch!!
> >
> > How is this worse than list(itertools.count()) ?
>
> list(itertools.count()) will eventually fail with a MemoryError.
>
> Actually len(itertools.count()) would as well - when a couple of long
> instances used up everything available - but it would take a *lot*
> longer.
>
> Tim Delaney

That's more of a theoretical argument on why the latter is worse. How
many real-world programs are prepared for MemoryError every time they
call list(), catch it and handle it graciously ? I'd say that the only
reason an exception would be preferable in such case would be
debugging; it's nice to have an informative traceback instead of a
program that entered an infinite loop.

George




More information about the Python-list mailing list