Skip to content

Python filter list of objects

  • by

You can use filter a built-in function with lambda to filter a list of objects in Python. The lambda function should access an attribute on the supplied object and check for a condition.

Another way is to use a list comprehension to iterate over the list of objects. Access an attribute and check if its value meets a condition. The new list will only contain the objects that meet the condition.

Python filter list of objects example

Simple example code Filter list of objects with the condition in Python

class Employee():

def __init__(self, name, salary):
self.name = name
self.salary = salary

def __repr__(self):
return self.name


alice = Employee('John', 100)
bob = Employee('Mike', 70)
carl = Employee('Carl', 150)

list_of_objects = [alice, bob, carl]

filtered_list = list(
filter(
lambda obj: obj.salary > 80,
list_of_objects
)
)

print(filtered_list)

Output:

Python filter list of objects example

Use a list comprehension to iterate over the list of objects

filtered_list = [
obj for obj in list_of_objects
if obj.salary > 80
]

using a for loop

for obj in list_of_objects:
    if obj.name in acceptable_names:
        filtered_list.append(obj)

Do comment if you have any doubts or suggestions on this Python filter topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading