How to Use the Python filter() Function

Contents
In this article, you will learn how to use the Python filter() function.
Python filter() Function
The filter() function in Python is used to filter out elements from an iterable (such as a list or tuple) based on a certain condition. It returns a filter object, which is an iterator that contains the elements from the iterable that satisfy the given condition.
Syntax
The syntax for filter() function is as follows:
filter(function, iterable)
Parameters
function
: A function that returns a Boolean value.iterable
: The iterable object that you want to filter.
Example
Here’s an example that shows how to use the filter() function to filter out even numbers from a list:
# define the list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# define the function that returns True for even numbers
def is_even(n):
return n % 2 == 0
# use the filter() function to filter out even numbers
filtered_numbers = list(filter(is_even, numbers))
# print the filtered list
print(filtered_numbers)
# Output: [2, 4, 6, 8, 10]
In this example, we define a list numbers and a function is_even() that returns True if a given number is even. We then use the filter() function to filter out the even numbers from the numbers list and store the result in the filtered_numbers list. Finally, we print the filtered list.
You can also use a lambda function to define the condition to filter the iterable:
# define the list
fruits = ['apple', 'banana', 'cherry', 'orange']
# use the filter() function with a lambda function to filter out elements that start with 'a'
filtered_fruits = list(filter(lambda x: x[0] != 'a', fruits))
# print the filtered list
print(filtered_fruits)
# Output: ['banana', 'cherry', 'orange']
In this example, we define a list fruits and use a lambda function inside the filter() function to filter out the fruits that start with the letter ‘a’. We then store the result in the filtered_fruits list and print it.