Updated April 14, 2023
Introduction to Python Filter Function
The filter function is one of the programming primitives that you can use in Python programs. It’s built-in to Python that offers an elegant way to filter out all the elements of a sequence for which the function returns True using Lambda expressions. Unlike the map function, the filter function requires only one iterable.
What are Lambda Expressions?
A lambda expression is an anonymous, in-line declaration of a function, usually passed as an argument. It can do anything a regular function can, except it can’t be called outside of the line where it was defined since it is anonymous: it has no name. Lambda functions are quite useful when you require a short, throwaway anonymous function. Something simple that you will only use once. Common applications are sorting and filtering data.
lambda arguments: expression
Type a keyword Lambda followed by zero or more inputs. Just like functions, it is perfectly acceptable to have anonymous functions with no inputs. Next, type a colon. Then finally, you enter a single expression. This expression is a return value. You cannot use Lambda expressions for multi-line functions.
Syntax of filter():
filter (function, iterable)
Filter Parameters :
The filter function takes two parameters:
- Function: Function that tests if elements of an iterable are True or false. If none, the function defaults to identity function returning false if any elements are false.
- Iterable: Iterable which is to be filtered could be sets, tuples, lists or containers of any iterators.
Examples to Understand Python Filter Function
Let’s discuss the Python Filter Function:
Filtering values above average.
Example #1
Code:
import statistics
data = [1,3,5,7,11,17] #The short list of data is collected from a nearby fuel sensor.
avg= statistics.mean (data)
new =filter(lambda x : x > avg, data)
print(new)
new =list(filter(lambda x: x>avg, data))
print(new)
- First, import the statistics module since it contains the mean function.
- Let us compute the average of this data.
- Then display the average so that you can see that the filter works as intended.
- Now we use the filter function to select the data greater than the average.
- We create an anonymous function that creates the input (Lambda expressions) to see if it is above average.
- Next, pass in the last of the data.
- The filter() will only return the data for which the function is true.
Output:
Pretty neat, huh! Let’s see a few more.
Note:
If brevity is in a soul of wit, then Python is a class by itself.
Quick Fact: If you have Python 3.x version, the filter method returns a generator, i.e., which can be traversed through. If you’re using the Python 2.x version, the filter method returns a list.
Example #2
Consider a program that filters out odd and even numbers.
Code:
Fibnocci = [0,1,1,2,3,5,8,12,21,34,55]
odd_numbers = list (filter (lambda x : x %2, Fibnocci))
print (odd_numbers)
even_numbers = list (filter(lambda x : x%2 == 0, Fibnocci))
print(even_numbers)
Output:
Example #3
What happens when the None value is passing the parameter?
A list of random data has been created below, which consists of strings, integers, and Boolean values. When the function parameter to the filter is None, it filters out data based on whether the element is True or False and returns accordingly.
Code:
New_list = [0, 1, 'a', 'B', False, True, '0', '4']
filtered_list = filter (None, New_list)
print('Filtered elements')
for element in filtered_list:
print(element)
Output:
In Python, the values that are treated as false are the empty string “, zero 0, an empty list [], empty tuple (), empty dictionary {}, false, none, and those objects that gesture Python that it is a trivial instance.
But be careful while using the filter function in this way. Like, zero 0 is a valid piece of data in most situations, and I would not want to filter it out.
Wondered if there is any such function that filters false items?
Yes, indeed.
Itertools. Ifilterfalse (function, iterable)
Conclusion
The map, filter and reduce functions greatly simplify the process of working with lists and other iterable collections of data; in fact, if you use lambda expressions, your work can often be done in a single line. After you master these functions, you will realize Python should be a comedian because it is full of a one-liner.
Recommended Articles
We hope that this EDUCBA information on “Python Filter Function” was beneficial to you. You can view EDUCBA’s recommended articles for more information.