Python Filter Function Tutorial (Simple Guide)

0
100
python filter function

The filter function is best used for applying a Boolean function to all items of a sequence (e.g. list, tuple etc)  with the objective of returning only the items which satisfy the condition = True.

(Note: A Boolean function returns either a true or false value).

The filter function only returns items that satisfies a condition.

So if you have the objective of extracting specific items from a sequence then filter might be the best solution. 

The filter function takes the form:

filter(function,sequence)

Let’s illustrate how it works:

Let’s say you have a list:

l= [1a’2‘b’3‘c’]

and we have the Boolean function that will determine if an item is an integer or not:

def integer(x):

if type(x)==int:

return True 

Using the filter function  will return only the items which have met the integer condition:

filter(integer, l)

will output:

[1,2,3]

With filter functions, most of the time the lambda expression is used rather than defining a Boolean function first.

For example, let’s say we want to extract only the string items from the same list l:

filter(lambda x: type(x)==str, l)

will output:

[‘a’, ‘b’, ‘c’]

Just like map and reduce functions, the use of lambda expression is for the purpose of saving time.

If you are just going to use a function once, no need to define it just to use the filter function. Just use lambda instead.

It is also important to point out that, Filter resembles a for loop but a simpler version.

So there is the simple explanation of the filter. Now that you have grasped the concept apply it to more complicated problems.

The filter function is really powerful when used together with map and reduce functions.

Check out the map and reduce functions.

For more information go to the official Python documentation:

https://docs.python.org/2/tutorial/datastructures.html

LEAVE A REPLY

Please enter your comment!
Please enter your name here