Site icon DataFlair

Python Program to Use Filter() 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 to selectively include elements from a list based on specific criteria defined by user-defined functions. The program focuses on filtering elements from a list based on whether they are prime numbers. This example demonstrates how the filter function can be employed to create a new list containing only elements that meet a specific condition.

Prerequisites

Topic Explanation

This program introduces two essential functions: ‘even_odd(n)’ for verifying number parity and ‘prime_no(n)’ for identifying prime numbers. It begins by creating a list named ‘mylist,’ populated with numerical values. The program then employs the ‘filter’ function in conjunction with ‘prime_no’ to generate a new list, ‘mylist1,’ comprising solely of prime numbers extracted from the initial list.

By combining these functions, the program provides a clear illustration of how to employ Python’s ‘filter’ function effectively for extracting specific elements from a list. Readers can grasp the practical application of ‘filter’ in isolating prime numbers, further enhancing their understanding of Python’s functional programming capabilities and list manipulation techniques.

Program

Code:

# Below Function check if a n is even or odd
def checkEvenOdd(n):
    return n % 2 == 0

#Below Function check if a n is prime or not
def prime_no(n):
    i = 2
    f = 0
    while i < n:
        if n % i == 0:
            f = 1
        i += 1
    return f == 0

# List of numbers
mylist = [10, 7, 8, 12, 9, 33, 45, 13, 15, 17]

# Filtering prime numbers from the list
mylist1 = list(filter(prime_no, mylist))

# Printing the list of prime numbers
print(mylist1)
Output:
[7, 13, 17]

Code Explanation:

Summary

In summary, this Python program offers a practical example of using the filter function to selectively include elements in a new list based on a specific condition defined by user-defined functions. It demonstrates how this function can be a powerful tool for data manipulation in Python, allowing developers to create refined lists based on specific criteria. Understanding the filter function expands one’s ability to work with data structures and apply custom conditions for filtering elements.

Exit mobile version