Iterator length

George Sakkis george.sakkis at gmail.com
Thu Jan 18 19:40:58 EST 2007


bearophileHUGS at lycos.com wrote:

> Often I need to tell the len of an iterator, this is a stupid example:
>
> >>> l = (i for i in xrange(100) if i&1)
>
> len isn't able to tell it:
>
> >>> len(l)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: object of type 'generator' has no len()
>
> This is a bad solution, it may need too much memory, etc:
>
> >>> len(list(l))
>
> This is a simple solution in a modern Python:
>
> >>> sum(1 for _ in l)
> 50
>
> This is a faster solution (and Psyco helps even more):
>
> def leniter(iterator):
>     """leniter(iterator): return the length of an iterator,
>     consuming it."""
>     if hasattr(iterator, "__len__"):
>         return len(iterator)
>     nelements = 0
>     for _ in iterator:
>         nelements += 1
>     return nelements
>
> Is it a good idea to extend the functionalities of the built-in len
> function to cover such situation too?
>
> Bye,
> bearophile

Is this a rhetorical question ? If not, try this:

>>> x = (i for i in xrange(100) if i&1)
>>> if leniter(x): print x.next()

George




More information about the Python-list mailing list