Home »
Python
Python | Lambda and filter() with Example
Python lambda and filter() with Example: Here, we are going to learn how to use filter() with lambda in Python?
Submitted by Pankaj Singh, on October 12, 2018
The filter() function is used to filter the elements from given iterable collection based on applied function.
Example:
Given a list of integers and we have to filter EVEN integers using 1) normal way and 2) lambda and filter().
1) 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]
2) 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]
Python Tutorial