What's the shortest way to count the number of items in a generator/iterator?

Fred Foo picture Fred Foo · Mar 21, 2011 · Viewed 35.2k times · Source

If I want the number of items in an iterable without caring about the elements themselves, what would be the pythonic way to get that? Right now, I would define

def ilen(it):
    return sum(itertools.imap(lambda _: 1, it))    # or just map in Python 3

but I understand lambda is close to being considered harmful, and lambda _: 1 certainly isn't pretty.

(The use case of this is counting the number of lines in a text file matching a regex, i.e. grep -c.)

Answer

Sven Marnach picture Sven Marnach · Mar 21, 2011

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.