How to use filter function in Python
Published on Aug. 22, 2023, 12:16 p.m.
The filter()
function in Python is used to filter items from any iterable (list, tuple, dictionary etc.) based on a condition defined by a function. The filter()
function returns a new iterable (iterator) that can be used to iterate over the items that satisfy the condition. The general syntax of filter()
function is as follows:
filter(function, iterable)
Here, function
is the function that needs to be applied to each element of the iterable
, and iterable
is the sequence that needs to be filtered. The function
should return True
or False
for each element of the iterable
, based on which the filtering is done.
Here’s an example that demonstrates how to use the filter()
function in Python:
def is_even(num):
return num % 2 == 0
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(is_even, my_list))
print(even_numbers) # Output: [2, 4, 6, 8, 10]
In this example, we define a function is_even
that takes a number as input and returns True
if the number is even. We then define a list my_list
containing some numbers (from 1 to 10). We use the filter()
function to filter the even numbers from the list my_list
using the is_even()
function. Finally, we convert the result into a list and print it.
In this way, you can use the filter()
function to filter items from any iterable based on a condition.