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
.)
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.