Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the length of a "filter" object in python

>>> n = [1,2,3,4]  >>> filter(lambda x:x>3,n) <filter object at 0x0000000002FDBBA8>  >>> len(filter(lambda x:x>3,n)) Traceback (most recent call last):   File "<pyshell#3>", line 1, in <module>     len(filter(lambda x:x>3,n)) TypeError: object of type 'filter' has no len() 

I could not get the length of the list I got. So I tried saving it to a variable, like this...

>>> l = filter(lambda x:x>3,n) >>> len(l) Traceback (most recent call last):   File "<pyshell#5>", line 1, in <module>     len(l) TypeError: object of type 'filter' has no len() 

Instead of using a loop, is there any way to get the length of this?

like image 885
Srichakradhar Avatar asked Oct 04 '13 13:10

Srichakradhar


People also ask

How do you find the length of an object in Python?

The function len() is one of Python's built-in functions. It returns the length of an object. For example, it can return the number of items in a list.

How do you find filtered objects in Python?

Try it out: # lambda is used in place of a function print(filter(lambda x: x % 2 != 0, [1, 3, 10, 45, 6, 50])) print(list(filter(bool, [10, "", "py"]))) import os # display all files in the current directory (except the hidden ones) print(list(filter(lambda x: x. startswith(".") !=

What does filter () do in Python?

Python filter() Function The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.

How do you filter an array of objects in Python?

You can select attributes of a class using the dot notation. Suppose arr is an array of ProjectFile objects. Now you filter for SomeCocoapod using. NB: This returns a filter object, which is a generator.


2 Answers

This is an old question, but I think this question needs an answer using the map-reduce ideology. So here:

from functools import reduce  def 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.

like image 24
Al Hoo Avatar answered Sep 30 '22 17:09

Al Hoo


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.

like image 192
arshajii Avatar answered Sep 30 '22 17:09

arshajii