Menu Close

Python filter() Function

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 a 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 fulfills the specific condition.

Python filter() function

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

Syntax

The syntax of the 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 returns an iterator.

Python filter() example

Here we will use the python filter function along with examples.

Example 1:

Suppose we have some candidates’ age list, and we want to filter only those ages, that is 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 a 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. As we know that filter() takes two parameters, function and iterable, and applies a function on each item of the iterable. After applying the function each item of the iterable ( list, tuple, set, etc) returns an iterable which can iterate through Python for a 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

Thanks for your valuable time…🙏🙏❤️❤️

Python itertools Module Tutorial
Python dir Function

Related Posts