itertools.ilen?

Jeremy Fincher fincher.* at osu.edu
Thu Aug 7 06:08:12 EDT 2003


Terry Reedy wrote:
> An iterator is a function/method that traverses (or possibly
> generates) a seqeuence.  The sequence has a length (actual or
> potential) but the iterator does not.

Even some sequences don't have a length; consider (Lisp terminology)
"improper lists," where the cdr points to a cell earlier in the list.  Or
any class with a somehow non-terminating __len__.

> Alternative: initialize six counters to 0.  Scan list once and update
> appropriate counter.

Yes, that works in this particular case, and is probably a superior
solution.

> If you mean a c-coded counter (which would not be an iterator itself)
> equivalent to the above, that could be done.  Perhaps len() could be
> upgraded/extended to accept an iterator and count when it can't get a
> __len__ method to call.  The main downside is that iterators are
> sometimes destructive (run once only).

That's why I don't think such a change should be made to len(); *all*
iterators are destructive and len() silently destroying them doesn't seem
generally useful enough for the potential for mistake.

> In the meanwhile, is this really a bottleneck for you? or merely the
> 'pity' of a program running in 1 sec when 0.1 is possible?

The whole of itertools really seems to exist because of the "pity" of taking
efficient iterators and turning them into lists in order to do any
significant manipulation of them.  In that case, I would imagine the pity
of having to turn an interator into a sequence in order to determine the
length of the underlying sequence would be reason enough.

Jeremy





More information about the Python-list mailing list