Filter a list of objects by a property in Python

To filter a list of objects by a property in Python, you can use a list comprehension. Here is an example demonstrating how to filter a list of objects by a specific property:

# Define a sample class
class Employee:
    def __init__(self, name, department, salary):
        self.name = name
        self.department = department
        self.salary = salary

# Create a list of Employee objects
employees = [
    Employee("Alice", "HR", 60000),
    Employee("Bob", "IT", 75000),
    Employee("Charlie", "HR", 55000),
    Employee("David", "IT", 80000),
    Employee("Eve", "Finance", 65000)
]

# Filter the list by department
filtered_employees = [employee for employee in employees if employee.department == "HR"]

# Print the filtered list
for employee in filtered_employees:
    print(f"Name: {employee.name}, Department: {employee.department}, Salary: {employee.salary}")

In this example, we define a class Employee and create a list of Employee objects. We then use a list comprehension to filter the list by the department property, keeping only the employees who work in the “HR” department. Finally, we print the details of the filtered employees.

You can modify the filter condition inside the list comprehension to filter by any other property or criteria.