[Python-ideas] iterator length

Nick Coghlan ncoghlan at gmail.com
Tue Aug 10 04:37:32 CEST 2010

On Tue, Aug 10, 2010 at 7:42 AM, Ivan Pozdeev <vano at mail.mipt.ru> wrote:
>> Hello,
>> Sometimes it's useful to get the number of elements yield by an
>> iterator. For example (if ilen is the name of the function):
> A generic iterator is something that inherently, by definition, has
> unknown and unpredictable length
> (think, for example, about berries you gather in a forest).
> There is no guarantee two tries give the same results,
> there isn't even a guarantee that it's finite.

Indeed - iterating over a completely arbitrary iterator with no exit
criteria is a recipe for infinite loops when someone passes in
something like itertools.count or itertools.repeat.

> You just can't, absolutely, by any means, know its length otherwise
> than by exhausting it. If you can, it's not a generic iterator but
> something else.

Yep, hence the existence of the __length_hint__ API as an internal
optimisation when dealing with iterators that do have some idea of
their length (see
http://mail.python.org/pipermail/python-dev/2009-April/088108.html for
discussion as to why it is undocumented).


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list