×


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 False
else:
return True
number = filter(func, num)
for x in number:
print(x)

It's Output is given below:

3
5
1
2
6


2. Filter even numbers:

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

It's Output is:

2
8
6


3. filters vowels

# filters vowels
def vowel(x):
vowels = ['a', 'e', 'i', 'o', 'u']
if (x in vowels):
return True
else:
return False
# sequence
letters = ['a', 'g', 'h', 'i', 'k']
# using filter()
filtered = filter(vowel, letters)
for x in filtered:
print(x)

Output will give:

a
i


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 list
even_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().


[Need support to fix Python function issues ? We can help .]


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.