05-17-2022, 03:32 PM
Filters In Python:
Filter function filters the iterables means it will return those items on which the given condition is true
Code:
#program to print each even number of list
mylist = [1,2,3,4,5,6,7,8,9]
mylist = list(filter(lambda x: x%2==0, mylist))
print(mylist)
It is not necessary to use lambda functions; you can also create your own functions and call them as an argument in the filter function just like this.
Code:
mylist = [1,2,3,4,5,6,7,8,9]
def greaterThan(num):
return num > 5
list_2 = list(filter(greaterThan,mylist))
print(list_2)
But using lambda functions make it easy to write code and readable.
Note: We use filters with iterables like list, tuple etc..