45 filter() method in python

 

'''

1. The filter() method filters the given sequence with the help of a function and 

retun filter object.

2. filter taks two parameters one is function another one is iterable object

'''


Use lambda function with filter()

The Python built-in filter() function accepts a function and a list as an argument. 

It provides an effective way to filter out all elements of the sequence. 

It returns the new sequence in which the function evaluates to True.



## Filter with lambda function

fo = filter(lambda a: a % 2 == 0 ,[1,2,6,4,5])

print(list(fo))



#program to filter out the tuple which contains odd numbers    

lst = (10,22,37,41,100,123,29)  

oddlist = tuple(filter(lambda x:(x%3 == 0),lst)) # the tuple contains all the items of the tuple for which the lambda function evaluates to true    

print(oddlist)  


Comments

Popular posts from this blog

39 abstract method in python

10 Interview question on python

4 Tuple data types