[New-bugs-announce] [issue9547] iterator length

Alexandru Moșoi report at bugs.python.org
Mon Aug 9 18:16:01 CEST 2010

New submission from Alexandru Moșoi <alexandru at mosoi.ro>:

Sometimes it's useful to get the number of elements yield by an iterator. For example (if ilen is the name of the function):

def pi(n):
  return ilen(for e in xrange(n) if isprime(e))

def count_pred(pred, iterator):
  return ilen(itertools.ifilter(pred, iterator))

Two notable solutions are discussed here http://stackoverflow.com/questions/3393431/how-to-counting-not-0-elements-in-an-iterable

1) sum(1 for e in iterator)
2) len(list(iterator))

First solution is slow, the second solution uses O(N) extra memory.

I propose the addition of a new function ilen() which is functionally equivalent to:

def ilen(iterator):
  return sum(1 for e in iterator)

This function should be different from len() because it's time complexity is O(N) (most people assume that len() takes O(1)) and it consumes the iterator.

messages: 113421
nosy: Alexandru.Moșoi
priority: normal
severity: normal
status: open
title: iterator length
type: feature request
versions: Python 2.5, Python 2.6, Python 2.7, Python 3.1, Python 3.2, Python 3.3

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list