×

Python filter() Function - Explained with Examples

The filter() function helps the user to filter a sequence of elements according to the given condition to check if it is true or not. This function helps to filter elements in the sequence faster and more accurately. And the filtered-out elements are sorted in the original order.

Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to perform related Python functions queries.

In this context, we shall look into using the filter() function in Python.

What is the filter() function in Python ?

The filter() function prints the result according to the accepted condition.

It's syntax is given below:

`filter(function, iterable)`

Python filter() function Parameter Values:

• function: function to check element.
• iterable: sequence to be filtered.

Examples of using filter() function

1. Take a look at the below function to Filter numbers less than or equal to 6:

`num = [3, 7, 5, 9, 1, 2, 8, 6]def func(x):if x > 6:return Falseelse:return Truenumber = filter(func, num)for x in number:print(x)`

It's Output is given below:

`35126`

2. Filter even numbers:

`num = [3, 7, 5, 9, 1, 2, 8, 6]def even(x):if x % 2 == 0:return Trueelse:return Falsenumber = filter(even, num)for x in number:print(x)`

It's Output is:

`286`

3. filters vowels

`# filters vowelsdef vowel(x):vowels = ['a', 'e', 'i', 'o', 'u']if (x in vowels):return Trueelse:return False# sequenceletters = ['a', 'g', 'h', 'i', 'k']# using filter()filtered = filter(vowel, letters)for x in filtered:print(x)`

Output will give:

`ai`

4. Using Lambda Function Inside filter():

`numbers = [1, 2, 3, 4, 5, 6, 7]# the lambda function returns True for even numbers even_numbers_iterator = filter(lambda x: (x%2 == 0), numbers)# converting to listeven_numbers = list(even_numbers_iterator)print(even_numbers)`

The Output will be:

`[2, 4, 6]`

Here, we have directly passed a lambda function inside filter().

Conclusion

This article covers how to use the filter() function in Python. In tact, the filter() function extracts elements from an iterable (list, tuple etc.) for which a function returns True.

filter() Arguments

The filter() function takes two arguments:

• function - a function.
• iterable - an iterable like sets, lists, tuples etc.