user380772
user380772

Reputation:

Counting number of yields by an iterator?

One can consider the functions

def f(iterator):
    count = 0
    for _ in iterator:
        count += 1
    return count

def g(iterator):
    return len(tuple(iterator))

I believe the only way they can differ is that g might run out of memory while f doesn't.
Assuming I'm right about that:

Is there a faster and/or otherwise-better (roughly, shorter without becoming code-golf) way to get f(iterator) while using less memory than tuple(iterator) takes up, preferably inline rather than as a function?

(If there is some other way for f, g ​to differ, then I believe that f is more likely than g to properly define the functionality I'm after. I already looked at the itertools documentation page, and don't see any solution there.)

Upvotes: 1

Views: 546

Answers (1)

niemmi
niemmi

Reputation: 17263

You can use sum with generator expression yielding 1 for every item in iterator:

>>> it = (i for i in range(4))
>>> sum(1 for _ in it)
4

Upvotes: 3

Related Questions