Python filter(lambda) is possible because you can use the Lambda function inside the filter() built-in function. The filter
method filters elements from an iterable that meets a specific condition.
The lambda
functions inline and anonymous functions in Python. These functions can be used along with the filter
method.
filter(lambda x: x , inp_list)
Python filter lambda example
Simple example code filters all the values from the list that is less than or equal to 20
. Each value of the list is passed to the lambda
function. If it returns True
, the value is added to the result; otherwise, not.
lst = [11, 23, 13, 4, 15, 66, 7, 8, 99, 10]
res = list(filter(lambda x: x <= 20, lst))
print(res)
print(type(res))
Output:
Filter All the Even Numbers
list(filter(lambda x : x % 2 == 0, list))
Filter All the Odd Numbers
list(filter(lambda x : x % 2 == 1, list))
Do comment if you have any doubts or suggestions on this Python filter topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.