Python program to see the working of filter() method

Here, we will see an example on the filter() method on objects in Python.
Submitted by Shivang Yadav, on February 18, 2021

The filter() Method

The filter() method in Python is used to filter elements of the data structure using a conditional function's truthy value.

The conditional function must return a Boolean value i.e. the returned values should be either true or false.

Syntax:

filter (function, iterable)

Parameters:

The function accepts two parameters.

  • function: The Boolean function that checks for the values.
  • iterable: An iterable on a data structure to pass values to the function.

Return value:

The method returns an iterable after filtering off the values from using the function.

Class and method used:

  • Class : Student
    • Method : getStudentInfo() : gets input of the student information from the user.
    • Method : printStudentInfo() : print in student information to the screen.
    • Method : search() : To return whether the student has qualified or not based on the inputted min percentage.
    • Variable : rollno : To store roll number of the student.
    • Variable : name : To store name of the student.
    • Variable : percentage : To store the percentage of the student.

Program to illustrate the working of filter method

class Student:
    def getStudentInfo(self):
        self.__rollno = input("Enter Roll No : ")
        self.__name = input("Enter Name : ")
        self.__percentage = int(input("Enter percentage : "))
    
    def printStudentInfo(self):
        print("Roll Number : ", self.__rollno, end = " ")
        print("Name : ", self.__name, end = " ")
        print("percentage : ", self.__percentage, end = " ")
    
    def Search(self,minMarks):
        if(self.__percentage >= minMarks ):
            return True
        else:
            return False

studentList = list()

while(True):
    student=Student()
    student.getStudentInfo()
    studentList.append(student)
    
    ch=input("Continue y/n?")
    if ch=='n':
        break

minPercent =int(input("Enter Qualifying Percentage: "))

FL=list(filter(lambda s:s.Search(minPercent),studentList))
if(len(FL)==0):
    print('No Record Exist')
else:
    print(" Students qualified are : ")

for s in FL:
    s.printStudentInfo()

Output:

Enter Roll No : 101
Enter Name : Shivang Yadav
Enter percentage : 87
Continue y/n?y
Enter Roll No : 102
Enter Name : Amit
Enter percentage : 75
Continue y/n?y
Enter Roll No : 103
Enter Name : Ankur
Enter percentage : 85
Continue y/n?n
Enter Qualifying Percentage: 80
 Students qualified are :
Roll Number :  101 Name :  Shivang Yadav percentage :  87 Roll Number :  103 Name :  Ankur percentage :  85

Python class & object programs »



Related Programs



Comments and Discussions!

Load comments ↻





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