Site icon DataFlair

Python Program on Filter Function with Lambda Function

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

In this article, we will explore a Python program that utilizes the filter function with lambda expressions. Lambda expressions, also known as anonymous functions, provide a concise way to create small, one-line functions. The program focuses on using the filter function with lambda expressions to selectively include elements from a list and characters from a string based on specific conditions.

Prerequisites

Topic Explanation

This program starts by creating a list, ‘mylist,’ comprised of numeric elements and a string, ‘mystring.’ It effectively utilizes the ‘filter’ function in combination with a lambda expression to establish ‘mylist1,’ a new list exclusively housing even numbers extracted from the original list.

Similarly, the program employs ‘filter’ with a lambda expression to generate ‘str1,’ a fresh list encompassing solely the vowels found within the initial string. This dual demonstration showcases the flexibility of the ‘filter’ function in processing both numerical and textual data, enhancing readers’ understanding of Python’s functional capabilities and list/string manipulation.

Program Code:

# Filter function with lambda expression

# List of integers
mylist = [10, 7, 8, 12, 66, 23, 88, 67]

# Filtering even numbers using lambda expression
mylist1 = list(filter(lambda x: (x % 2 == 0), mylist))

# Printing the filtered list of even numbers
print(mylist1)

# String for vowel filtering
mystring = "Data Flair provide free course"

# Filtering vowels using lambda expression
str1 = list(filter(lambda v: (v == 'a' or v == 'e' or v == 'i' or v == 'o' or v == 'u'), mystring))

# Printing the filtered list of vowels
print(str1)
Output:
[10, 8, 12, 66, 88]
[‘a’, ‘a’, ‘a’, ‘i’, ‘o’, ‘i’, ‘e’, ‘e’, ‘e’, ‘o’, ‘u’, ‘e’]

Code Explanation:

Summary

In summary, this Python program offers a practical example of using the filter function with lambda expressions for selective element inclusion. It demonstrates how lambda expressions can be employed for concise and efficient conditions, making the code more readable and expressive. Understanding the filter function and lambda expressions enhances one’s ability to manipulate data structures and apply custom conditions for filtering elements.

Exit mobile version