Can any one explain filter function in python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 6

Can any one explain filter function in python?

4th Sep 2020, 4:52 AM
Ponnam Mahija
3 Answers
+ 8
It just removes all the elements from a list that don't match the condition! x = [1,2,3,4,5,6,7,8,9,10] # instead of using for loop and if conditions! You can easily extract a list having only the even elements! # x = list(filter(condition, listname)) # if the condition is true then it will add on to the newly filtered list # don't forget to add that list function because filter returns a generator and we want a list x = list(filter(lambda i: i%2==0, x)) print(x) output: [2,4,6,8,10] Click here to get more info about maps and filters https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2461/
4th Sep 2020, 5:04 AM
Namit Jain
Namit Jain - avatar
4th Sep 2020, 7:56 AM
KillĂș
KillĂș - avatar
+ 4
'filter' is a function that takes two arguments : - a predicate (function that returns True or False) - an iterable element (it can be a list, a tuple, a range object, a map object) 'filter' returns an iterable 'filter' object. filter(predicate, iterable) -> filter_obj For each element n of the iterable object, filter yields this element if and only if 'predicate(n)' is True.
4th Sep 2020, 5:08 AM
Théophile
Théophile - avatar