pythoniteratorgeneratoriterable

How can I count the number of items in an arbitrary iterable (such as a generator)?


Suppose I have an arbitrary iterable - for example, a generator that iterates over lines of a file and yields the ones matching a regex.

How can I count the number of items in that iterable, supposing that I don't care about the elements themselves?


Solution

  • Calls to itertools.imap() in Python 2 or map() in Python 3 can be replaced by equivalent generator expressions:

    sum(1 for dummy in it)
    

    This also uses a lazy generator, so it avoids materializing a full list of all iterator elements in memory.