Contents
Python Filter Function
Python filter() function is used to filter the elements of an iterable based on a function.
In this tutorial, we will learn the syntax and usage of filter() function, with the help of example programs.
Syntax – filter()
Following is the syntax of Python builtin filter() function.
filter(function, iterable)
where in for the first argument, you can pass a regular Python function or Python lambda function. For the second argument you can pass any collection that is iterable, for example, tuple, list, etc.
The function should return True or False. When True is returned for an element in the iterable, the element is included in the return value of filter(), else not.
Example 1: Python filter()
In this example, we will use filter() function to filter a list of numbers for only even numbers.
Python Program
def even(n) :
if n % 2 == 0 :
return True
else :
return False
list1 = [1, 2, 3, 4, 5, 6, 7, 8]
output = filter(even, list1)
for x in output:
print(x)
Run Output
2
4
6
8
Example 2: Python filter() with Lambda Function
In this example, we will use the same use case as above, but instead of a regular function we shall pass lambda function to filter() function.
Python Program
list1 = [1, 2, 3, 4, 5, 6, 7, 8]
output = filter(lambda n: True if n % 2 == 0 else False, list1)
for x in output:
print(x)
Run Output
2
4
6
8
Summary
Concluding this tutorial of Python Examples, we learned how to filter the elements of a given iterable based on a function.