Write a python program to search objects from an array of objects using filter() method
The python program defines a Person class and a list of Person objects. It then uses the filter() function to filter people in the list who are older than 25 years. Here's a breakdown of the code:
- class Person: This class defines a Person with attributes for name and age.
- The code creates a list of Person objects, people, with different names and ages.
- def is_older_than_25(person): This function defines a filtering criterion. It returns True if the person's age is greater than 25; otherwise, it returns False.
- filter(is_older_than_25, people): The filter() function takes the is_older_than_25 function and the list of people, and it returns an iterable containing only the Person objects for which the is_older_than_25 function returns True.
- filtered_people_list = list(filtered_people): This line converts the filtered iterable to a list. While this conversion is optional, it's done here to easily loop through the filtered results multiple times.
- The code then loops through the filtered list and prints the name and age of people older than 25.
Here's what the code does:
- It defines a class Person to represent people with their names and ages.
- It creates a list of Person objects.
- It uses the filter() function to filter and retrieve people older than 25.
- It converts the filtered result into a list (optional).
- It displays the names and ages of people older than 25.
Source Code
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Create an array of Person objects
people = [
Person("Kim", 21),
Person("Sam", 30),
Person("Charlie", 29),
Person("Bob", 25),
Person("Tiya", 27),
]
# Define a function to filter people older than a certain age
def is_older_than_25(person):
return person.age > 25
# Use the filter() method to search for people older than 25
filtered_people = filter(is_older_than_25, people)
# Convert the filtered result to a list (optional)
filtered_people_list = list(filtered_people)
# Display the filtered results without f-strings
print("People older than 25 :")
for person in filtered_people_list:
print("Name :", person.name)
print("Age :", person.age)
Output
People older than 25 :
Name : Sam
Age : 30
Name : Charlie
Age : 29
Name : Tiya
Age : 27