Get the length of a 'filter' object in Python


Borislav Hadzhiev

Last updated: Jun 26, 2022


Photo from Unsplash

Get the length of a 'filter' object in Python #

To get the length of a filter object in Python:

  1. Use the list() class to convert the filter object to a list.
  2. Pass the list to the len() function.
  3. The len function will return the number of items in the list.
my_list = [1, 3, 5, 7, 9] result = list(filter(lambda num: num > 3, my_list)) print(len(result)) # 👉️ 3
Filter objects cannot be passed directly to the len() function because in order to get the length of the filter object, we have to iterate through it.

The list class takes an iterable and returns a list object.

You can also use a list comprehension instead of the filter() function.
my_list = [1, 3, 5, 7, 9] result = [num for num in my_list if num > 3] print(len(result)) # 👉️ 3
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

Note that passing a filter object to the list class exhausts the iterator.
my_list = [1, 3, 5, 7, 9] result = filter(lambda num: num > 3, my_list) list_1 = list(result) print(list_1) # 👉️ [5, 7, 9] list_2 = list(result) print(list_2) # 👉️ []

If you need to convert a filter object to a list, do it directly and not in multiple places.

The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

If you pass None for the function argument, all falsy elements of the iterable are removed.

When we pass an object to the len() function, the object's __len__() method is called.

You can use the dir() function to print an object's attributes and look for the __len__ attribute.
my_list = [1, 3, 5, 7, 9] result = filter(lambda num: num > 3, my_list) # 👇️ ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', # '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', # '__iter__', '__le__', '__lt__', ...] print(dir(result))

Or you can check using a try/except statement.
my_list = [1, 3, 5, 7, 9] result = filter(lambda num: num > 3, my_list) try: print(result.__len__) except AttributeError: # 👇️ this runs print('object has no attribute __len__')

We try to access the object's __len__ attribute in the try block and if an AttributeError is raised, we know the object doesn't have a __len__ attribute and cannot be passed to the len() function.

The len() function returns the length (the number of items) of an object.
my_list = ['apple', 'banana', 'kiwi'] result = len(my_list) print(result) # 👉️ 3
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

If you aren't sure what type a variable stores, use the built-in type() class.
my_list = [1, 3, 5, 7, 9] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ True result = filter(lambda num: num > 3, my_list) print(type(result)) # 👉️ <class 'filter'> print(isinstance(result, filter)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.