+ 6
Can anyone explain the use of filter function in python
2 Antworten
+ 3
in python filter function makes a list with objects which is true in function. for exapmle usage of filter functions is
filter(function,list)
if you want to print
print(list(filter(function,list)))
a=[1,2,3,4,5] #create a list
def test(num): #create a function
return num%2==0
print(list(filter(test,a))) #filter
----output----
[2,4]
so we filtered the list and we created list with objects which is even
so filter function creates a list with objects which provides the function True
+ 2
filter() is a function that can take an iterable like a list, and use a function to select elements from the iterable. The function can be a lambda or user defined function. All elements of the iterable are tested against the lambda function and give True or False.
Here is a simple lambda function that checks for even numbers. If an element in the list is an odd number, it will not be handled, an even number will be stored in the nuns list.
nums = [11,22,33,44]
a = list(filter(lambda x: x%2==0, nums))
print(a) #[22, 44]