Author Alexandru.Moșoi
Recipients Alexandru.Moșoi
Date 2010-08-09.16:15:59
SpamBayes Score 4.64217e-06
Marked as misclassified No
Message-id <1281370561.47.0.585215134028.issue9547@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2010-08-09 16:16:01Alexandru.Moșoisetrecipients: + Alexandru.Moșoi
2010-08-09 16:16:01Alexandru.Moșoisetmessageid: <1281370561.47.0.585215134028.issue9547@psf.upfronthosting.co.za>
2010-08-09 16:15:59Alexandru.Moșoilinkissue9547 messages
2010-08-09 16:15:59Alexandru.Moșoicreate