Python filter() built-in function
From the Python 3 documentation
Introduction
The filter()
function in Python is a built-in function that allows you to process an iterable and extract those items that satisfy a certain condition. It returns an iterator with the elements that meet the criteria.
Syntax
filter(function, iterable)
- function: The function to execute for each item in the iterable. It should return
True
orFalse
for each item. - iterable: The iterable to filter, such as a list, tuple, or string.
Description
The filter()
function constructs an iterator from those elements of the iterable for which the function returns True
. If the function is None
, it removes all elements of the iterable that are false.
Example
>>> def is_even(num):
... return num % 2 == 0
...
>>> numbers = [1, 2, 3, 4, 5, 6]
>>> even_numbers = list(filter(is_even, numbers))
>>> print(even_numbers)
>>> [2, 4, 6]
In this example, the is_even
function is defined to determine whether a number is even or not. The filter method takes two arguments
: the first argument
is the function to apply to each element of the list, and the second argument
is the list to be filtered. The filter method returns an iterator, which is then converted to a list and stored in the even_numbers variable. The final output is the list of even numbers from the original list.
Relevant links
- map(): Apply a function to every item of an iterable and return an iterator of the results.
- iter(): Return an iterator object.
- List Comprehensions: A concise way to create lists, often used as an alternative to
filter()
. - Comprehensions
- Functions
- reduce()