Python Filter Function
Python - filter()
Python filter() built-in 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 of filter()
The syntax of Python builtin filter() function is given in the following.
filter(function, iterable)
where
Parameter | Description |
---|---|
function | A regular Python function or Python lambda function. |
iterable | Any collection that is iterable, for example, tuple, list, etc. |
The function
must return a boolean value of 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.
Examples
1. Filter even numbers in a list
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)
Output
2
4
6
8
2. 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)
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.