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


ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.