pythoniterator

Getting number of elements in an iterator in Python


Is there an efficient way to know how many elements are in an iterator in Python, in general, without iterating through each and counting?


Solution

  • No. It's not possible.

    Example:

    import random
    
    def gen(n):
        for i in xrange(n):
            if random.randint(0, 1) == 0:
                yield i
    
    iterator = gen(10)
    

    Length of iterator is unknown until you iterate through it.