Is there an efficient way to know how many elements are in an iterator in Python, in general, without iterating through each and counting?
This code should work:
>>> iter = (i for i in range(50))
>>> sum(1 for _ in iter)
50
Although it does iterate through each item and count them, it is the fastest way to do so.
It also works for when the iterator has no item:
>>> sum(1 for _ in range(0))
0
Of course, it runs forever for an infinite input, so remember that iterators can be infinite:
>>> sum(1 for _ in itertools.count())
[nothing happens, forever]
Also, be aware that the iterator will be exhausted by doing this, and further attempts to use it will see no elements. That's an unavoidable consequence of the Python iterator design. If you want to keep the elements, you'll have to store them in a list or something.