Skip to content

Python filter object

  • by

To filter objects in Python you can select attributes of a class using the dot notation. Suppose arr is an array of ProjectFile objects. Now you filter for SomeCocoapod using.

filter(lambda p: p.repo == "SomeCocoapod", arr)

NB: This returns a filter object, which is a generator. To have a filtered list back you can wrap it in a list constructor.

As a very Pythonic alternative, you can use list comprehensions:

filtered_arr = [p for p in arr if p.repo == "SomeCocoapod"]

Source: stackoverflow.com

Python filter object example

Simple example code.

class Employee():
def __init__(self, id):
self.id = id


list_of_objects = []

for i in range(5):
list_of_objects.append(Employee(i))

# print(list_of_objects)

for obj in list_of_objects:
print(obj.id)

res1 = filter(lambda emp: emp.id == 1, list_of_objects)
print(list(res1))

res2 = [p for p in list_of_objects if p.id == 1]
print(res2)

Output:

Python filter object example

Do comment if you have any doubts or suggestions on this Pytohn 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