Menu Close

Python filter() Function

In this tutorial, we are going through the python filter function to filter all the items of iterable with function.
Sometimes you want to filter the items of iterable that fulfill the specific condition, Then the filter function will be the best option for that.

In this guide, we will see how to filter each item of the iterable that fulfill the specific condition.

Python filter() function

Python filter function is a built-in function that returns an iterator, where the items filtered through the specific function.

Syntax

The syntax of python filter method is:-

filter(function, iterable)

Parameters

filter function in python accepts two parameters.

  • function:- Required, A function that applies to each item of iterable.
  • iterable:- A iterable to be filtered.

Return Value

filter function in python return a iterator.

Python filter() example

Here we will use python filter function along with examples.

Example 1:

Suppose we have some candidate’s age list, and we want to filter only those age, that are greater than 18.

age = [12, 20, 14, 30, 25, 28, 5, 30, 11,40, 80, 40, 23, 50, 78]
def filterAge(x):
	if x > 18:
		return True
	else:
		False				
result = filter(filterAge, age)
for i in result:
	print(i)

Output

20
30
25
28
30
40
80

Example 2:

We have list of some numbers and we want to filter only even numbers.

num = [12, 20, 14, 30, 25, 28, 5, 30, 11,40, 80, 40, 23, 50, 78]
def even(x):
	if x % 2 == 0:
		return True
	else:
		False				
result = filter(even, num)
print(list(result))

Output

[12, 20, 14, 30, 28, 30, 40, 80, 40, 50, 78]

Conclusion

In this article, we have learned the Python filter function to filter each item of the iterable using a function.
After filtered, each item of the iterable, the filter function in python returns an iterator that can be iterate through for loop.

If this article helped you, please share it with your friends who want to learn Python programming from scratch to advanced.

Other Python built-in functions


For more information:- Click Here

Previous Article
Next Article

Related Posts

Leave a Reply