How to find the length of a "filter" object in python
You have to iterate through the filter object somehow. One way is to convert it to a list:
l = list(filter(lambda x: x > 3, n))len(l) # <--
But that might defeat the point of using filter()
in the first place, since you could do this more easily with a list comprehension:
l = [x for x in n if x > 3]
Again, len(l)
will return the length.
This is an old question, but I think this question needs an answer using the map-reduce ideology. So here:
from functools import reducedef ilen(iterable): return reduce(lambda sum, element: sum + 1, iterable, 0)ilen(filter(lambda x: x > 3, n))
This is especially good if n
doesn't fit in the computer memory.
Converting a filter to a list will take extra memory, which may not be acceptable for large amounts of data. You can find length of the filter object without converting it to a list:
sum(1 for _ in filter(lambda x: x > 3, n))