Home »
Python
Python filter() with Lambda Function
By IncludeHelp Last updated : December 08, 2024
Python filter() with Lambda Function
The filter() function is used to filter the elements from given iterable collection based on applied function.
The lambda function is an anonymous function - that means the function which does not have any name.
Implementing filter() with lambda function
Given a list of integers and we have to filter EVEN integers using 1) normal way and 2) lambda and filter().
Approach 1: Using normal way
# function to find even number
def filtereven(data):
even = []
for n in data:
if n % 2 == 0:
even.append(n)
return even
# list of integers
fibo = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
print("Orignal List :", fibo)
# function call
even = filtereven(fibo)
print("Even List :", even)
Output
Orignal List : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Even List : [0, 2, 8, 34]
Approach 2: Using filter() with lambda
# list of integers
fibo = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
print("Orignal List :", fibo)
# filter even numbers using filter() and lambda
even = list(filter(lambda n: n % 2 == 0, fibo))
print("Even List :", even)
Output
Orignal List : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Even List : [0, 2, 8, 34]