filter function in Python
filter( ) in Python is used to apply an in-built or user defined or lambda functions to an iterator object (eg. lists, sets, tuples etc.) which will be used to filter our iterator object.
The output is a filtered generator object which needs to be converted to a Python object. It is highly useful to write shorter and elegant Python codes avoiding for loops.
Syntax: filter( function, iterator object)
where first argument i.e. function needs to return True or False, or zero or non-zero valueswhich will be used to filter our iterator object.
Understanding with examples
Let us create our list named salary:
salary = [4000,2565,2345,7653,1000,825]
Task: Filter only those salaries which are more than 4000.
For this let us create our UDF which takes a scalar and returns a scalar having True or False values.
def my_func(x): if x < 4000: return False else: return True
Now we will use this UDF my_func in our filter function:
Using lambda function:
We can achieve the same result by using lambda function:
In the following code we have used list comprehension:
Value_when_condition_is_true IF condition_to_be_evaluated ELSE value_when_condition_is_false
list(filter(lambda x: False if x< 4000 else True, salary))
Above lambda function returns the value False when salary is less than 4000, otherwise it will return True.
Task: Filter for the numbers which are divisible by 10:
mylist = [10,20,35,129,400] list(filter(lambda x: x%10 == 0, mylist))
Passing our function as None in filter( )
When we pass the function as None then it means return only non-zero and non-False elements (numbers or characters or True) , no other ib-built function or UDF or lambda function needs to be evaluated.
mylist = [4000,0,2345,7653,0,825,0,'a','b','c'] list(filter(None, mylist))