Getting number of elements in an iterator in Python

user248237 picture user248237 · Jul 27, 2010 · Viewed 133.6k times · Source

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

Answer

John Howard picture John Howard · Jul 27, 2010

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.