The filter
function in Python is a built-in utility designed to filter elements from an iterable based on a specified condition. It applies a predicate function to each item in the iterable and returns an iterator that includes only the items for which the predicate function returns True
. This makes filter
useful for selecting elements that meet certain criteria.
filter
Function WorksThe filter
function takes two arguments:
True
or False
.**predicate_function**
: The function that evaluates each item.**iterable**
: The iterable whose items are tested by the predicate function.Output:
In this example, filter
applies the is_even
function to each element in the numbers
list and returns only the even numbers.
filter
The filter
function can be used with lambda functions for concise filtering.
Output:
Here, a lambda function replaces the named is_even
function, providing the same result in a more compact form.
filter
with Other Functions**filter**
vs **map**
**filter**
: Used to include only those elements for which the predicate function returns True
.
**map**
: Applies a function to each item in an iterable and returns an iterator of the results.
Example of **map**
:
Output:
Here, map
applies the square
function to each element in the numbers
list, whereas filter
would have excluded numbers based on a condition.
**filter**
vs List ComprehensionBoth filter
and list comprehensions can be used to filter elements based on a condition. The choice between them often depends on readability and preference.
List Comprehension:
Output:
List comprehensions can be more readable for straightforward filtering tasks, while filter
is useful when working with existing predicate functions.
Output:
In this example, filter
selects words with more than 5 characters from the list.
Output:
This example filters out the even numbers from a range of values.
The filter
function in Python is a powerful tool for selecting elements from an iterable based on a specified condition. By applying a predicate function, filter
efficiently returns only the items that meet the criteria. While it shares similarities with functions like map
and list comprehensions, filter
excels in scenarios where the goal is to include items that satisfy a condition. Understanding how to use filter
effectively can enhance your ability to process and analyze data in Python.