Note

Python - filter() - Filter values from an iterable


Overview of the Python filter() function. Filter elements in an iterable.

filter(function, iterable) returns lazy iterator that applies function to each element of the iterable and leaves only elements that are truthy. Truthy values are values that evaluate to True.

That means, that filter() function will run provided function on each object of a given iterable and leave only elements that evaluates to True.


from typing import Any

my_list_1 = ["string", 1, 0.5, True, [1, 2], "yes"]


def check_if_string(value: Any) -> bool:
    return type(value) == str


string_iterator = filter(check_if_string, my_list_1)

for result in string_iterator:
    print(result)

Output:

string
yes

Explanation

  • The check_if_string() function checks if a given value is a string (str type).

  • filter() applies check_if_string() to each item in my_list_1 and only returns items that are strings.

  • string_iterator is a lazy iterator, generating values only when iterated over, making it efficient for large datasets.


If instead of a function, you will provide None, filter() will simply check if value evaluates to True:

my_list_2 = ["string", None, 0, False, [], 1]


another_filter = filter(None, my_list_2)

for result in another_filter:
    print(result)

Output:

string
1

Explanation:

  • Here, filter(None, my_list_2) keeps only the items in my_list_2 that are "truthy".

  • The filter() function excludes None, 0, False, and [] because these are "falsy" values in Python.


Key Points to Remember about filter()

  • Lazy Evaluation: filter() returns an iterator rather than a list, generating values only as needed. This makes it memory-efficient for handling large datasets.

  • Falsy vs. Truthy Values: By passing None as the function, filter() automatically excludes items that evaluate to False.

  • Custom Functions: When filtering based on specific conditions, defining a custom function allows you to control which items are included.

I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!

Thank You Image


You might also be interested in: