There are plenty of times that you have an iterator and you want to count how many items there are for the particular iterator. The fast intuitive way would be:
it = range(100) print('There are {} items in the iterator'.format(len(list(it))))
But, doing this it means that the list
is created and populated with all the items in the iterator. For 100 items, like the example, this would be no problem. But what about thousands of items or thousands of objects that consume lots of memory? Additionally, using the list with the iterator means that you constantly calling append to the list, until the iterator finishes.
To avoid all the above, you can use thee itertools and collections packages.
import itertools import collections elem_count = itertools.count() it = range(10000) collections.deque(zip(it, elem_count)) print('Iterator has {} elements'.format(next(elem_count)))