count items in generator

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


George Sakkis <george.sakkis at gmail.com> 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()) ?

It's a slightly worse trap because list(x) ALWAYS iterates on x (just
like "for y in x:"), while len(x) MAY OR MAY NOT iterate on x (under
Cameron's proposal; it currently never does).

Yes, there are other subtle traps of this ilk already in Python, such as
"if y in x:" -- this, too, may or may not iterate.  But the fact that a
potential problem exists in some corner cases need not be a good reason
to extend the problem to higher frequency;-).


Alex



More information about the Python-list mailing list