How to filter a list of Objects in Python?

Estimated read time 2 min read

To filter a list of objects in Python, you can use the filter() function or a list comprehension. Here’s how you can do it:

Method 1: Using the filter() function

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Create a list of Person objects
people = [
    Person("Alice", 25),
    Person("Bob", 30),
    Person("Charlie", 20),
    Person("David", 35)
]

# Filter the list based on a condition
filtered_people = list(filter(lambda person: person.age >= 30, people))

# Print the filtered list
for person in filtered_people:
    print(person.name, person.age)

Output:

Bob 30
David 35

In the above example, the filter() function is used to create a new list filtered_people by applying the lambda function as a filter condition. The lambda function checks if the age of each person is greater than or equal to 30. Finally, we iterate over the filtered list and print the name and age of each person.

Method 2: Using list comprehension

# Create a list of Person objects
people = [
    Person("Alice", 25),
    Person("Bob", 30),
    Person("Charlie", 20),
    Person("David", 35)
]

# Filter the list based on a condition using list comprehension
filtered_people = [person for person in people if person.age >= 30]

# Print the filtered list
for person in filtered_people:
    print(person.name, person.age)

The output will be the same as in the previous example.

Both methods achieve the same result, but using list comprehension often results in more concise and readable code.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply