Python filter example

The function filter(function, list) is used to filter elements in iterable for which function returns true.
First argument function will be applied to all elements of the list and the element for which function returns true will be included in the iterable.

Lets see some examples:

Now create a list of 20 numbers a below.

def odd_check(num): if num%2 ==1: return True lst =list(range(20)) print(list(filter(odd_check,lst)))

Output:

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

filter() is more commonly used with lambda functions, this because we usually use filter for a quick job where we don’t want to write an entire function.
Lets repeat the example above using a lambda expression:

lst =list(range(20)) print(list(filter(lambda x: x%2==1,lst)))

Output:

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Let’s write another example in which we are going to filter the word which starts with ‘M’.

String_lst=['John','Martin','Mary','David'] def startWithM(String_lst): for str in String_lst: if(str[0]=='M'): return True filtered_list=list(filter(startWithM,String_lst)) print(filtered_list)

Output:

[‘Martin’, ‘Mary’]

that’s all about python filter function.

Leave a Reply

Your email address will not be published. Required fields are marked *