Python program to filter even values from list using lambda function

Here, we will see function to filter even values from a list of Fibonacci numbers using lambda function.
Submitted by Shivang Yadav, on March 19, 2021

Lambda functions in Python are special functions available in python. They are anonymous functions i.e., without any function name. 

You can check even values by finding its remainder. If the remainder with 2 is 0, the number is even otherwise it's odd.

We will filter based on this logic and store the even value in a list and then print it.

Program to filter even values from list using regular function

# Python program to filter even value 

# Function to filter even values 
def filtereven(data):
    even=[]
    for n in data:
        if n%2==0:
            even.append(n)
    return even
# List of fibonacci values
fibo = [0,1,1,2,3,5,8,13,21,34,55]

print("List of fibonacci values :",fibo)
evenFibo = filtereven(fibo)
print("List of even fibonacci values :",evenFibo)

Output

List of fibonacci values : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
List of even fibonacci values : [0, 2, 8, 34]

Python program to filter even values using lambda function

# Python program to filter even value 
# using lambda function 

# List of fibonacci values
fibo = [0,1,1,2,3,5,8,13,21,34,55]
print("List of fibonacci values :",fibo)

# filtering even values using lambda function 
evenFibo = list(filter(lambda n:n%2==0,fibo))
print("List of even fibonacci values :",evenFibo)

Output

List of fibonacci values : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
List of even fibonacci values : [0, 2, 8, 34]

Python Lambda Function Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.