You can get a list of all matching elements with a list comprehension:

[x for x in myList if x.n == 30]  # list of all elements with .n==30

If you simply want to determine if the list contains any element that matches and do it (relatively) efficiently, you can do

def contains(list, filter):
    for x in list:
        if filter(x):
            return True
    return False

if contains(myList, lambda x: x.n == 3)  # True if any element has .n==3
    # do stuff
Answer from Adam Rosenfield on Stack Overflow
🌐
Paigeniedringhaus
paigeniedringhaus.com › blog › filter-merge-and-update-python-lists-based-on-object-attributes
Filter, Merge, and Update Python Lists Based on Object Attributes | Paige Niedringhaus
February 23, 2024 - I used Python’s built-in filter() function to iterate over the card_list passed to the function to create a new list named cards_for_sale. The anonymous lambda function inside of filter() takes each card in the card_list and returns True if the nft_price attribute of the card is not None, and False if it is - this is how it filters out all the cards that don’t have a price.
Discussions

Filtering list of objects on multiple conditions
Hi all, interested in your approaches and suggestions to this problem. Let's say I have created a custom Player class that contains many attributes… More on reddit.com
🌐 r/learnpython
4
1
July 27, 2023
dictionary - Python, Filter a List of Objects, but return a specific attribute? - Stack Overflow
In the case of object filtering ... list the attribute values) of the filtered list you can do the following using generators in a single statement (last line of code, the rest is there for instruction showing generating a large list of objects using matrix multiplication to generate constructor params) #!/usr/bin/env python import itertools ... More on stackoverflow.com
🌐 stackoverflow.com
April 25, 2017
Python filter a list of class objects by class method using Filter built-in function problem
The code runs fine here: https://i.imgur.com/kXq6AhX.png altough I must add that filter has been superseded by list comprehensions, I would advise to use filtered_list = [f for f in food_list if f.isfree()] More on reddit.com
🌐 r/learnpython
2
1
January 21, 2022
python - Filtering list of objects based on attribute - Stack Overflow
I have 4 objects. class MyObject: def __init__(self, id: int, result_name: str): self.id = id self.result = Result(result_name) class Result: def __init__(self, name: str): ... More on stackoverflow.com
🌐 stackoverflow.com
April 22, 2022
🌐
GitHub
github.com › python-attrs › attrs › issues › 444
Filter list of objects by attributes values · Issue #444 · python-attrs/attrs
September 14, 2018 - Would is possible to add a mecanism to filter objects like it is for asdict and astuple but that returns matching objects instead of attributes and values?
Author   python-attrs
🌐
Reddit
reddit.com › r/learnpython › filtering list of objects on multiple conditions
r/learnpython on Reddit: Filtering list of objects on multiple conditions
July 27, 2023 - I had a thought that this might be easier to by creating something like a PlayerFilter class which can be instantiated and then have filters added to a dict attribute or similar, and then can be applied to a list of players and return the filtered list. This seems more Pythonic to me but also seems slightly overkill and I'm looking for the most straightforward and intuitive way to filter these values.
🌐
LabEx
labex.io › tutorials › python-how-to-filter-list-by-element-properties-437810
How to filter list by element properties | LabEx
Learn advanced Python list filtering techniques to efficiently filter elements based on specific properties, using list comprehensions, filter() function, and lambda expressions.
🌐
EyeHunts
tutorial.eyehunts.com › home › python filter list of objects
Python filter list of objects - Tutorial - By EyeHunts
January 25, 2023 - 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.
🌐
YouTube
youtube.com › the python oracle
Python, Filter a List of Objects, but return a specific attribute? - YouTube
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn--Music by Eric Matyashttps://www.soundimage.orgTrack title: Puzzle G
Published   January 1, 2023
Views   17
Find elsewhere
🌐
Linux Manual Page
linux.die.net › diveintopython › html › power_of_introspection › filtering_lists.html
4.5. Filtering Lists
The whole filter expression returns ... expression is an identity expression, which it returns the value of each element. dir(object) returns a list of object's attributes and methods -- that's the list you're mapping....
🌐
Reddit
reddit.com › r/learnpython › python filter a list of class objects by class method using filter built-in function problem
r/learnpython on Reddit: Python filter a list of class objects by class method using Filter built-in function problem
January 21, 2022 -

Like ok... the title said it all. For example : I have a list filled by class name Food. The class uniqueness are defined by name and price attribute. And I create a method to check if the Food is free. the question is how do I use the method to filter the list of Food class using the free checking method of food class?

@dataclass
class Food:
    name : str
    price : int

    def isfree(self):
        return self.price == 0

food_list = [Food(name = "curry", price = 5), Food(name = "sushi", price = 0)]
filtered_list = filter(Food.isfree, food_list) # got error TypeError: isfree() takes 0 positional arguments but 2 were given
Top answer
1 of 2
1

You can do this very easily with a set:

class MyObject:
    def __init__(self, id_, result_name):
        self.id_ = id_
        self.result = Result(result_name)


class Result:
    def __init__(self, name):
        self.name = name

object1 = MyObject(1, 'A')
object2 = MyObject(2, 'A')
object3 = MyObject(3, 'B')
object4 = MyObject(4, 'B')

T = (object1, object2, object3, object4)

S = {o.result.name for o in T}

print(S)

Output:

{'A', 'B'}

Note:

You could obviously convert the set to a list if that's what you need.

Use of id not a great idea as a variable name

2 of 2
0

You can that using reduce from functools.

Let's start by creating the sample data:

class MyObject:
    def __init__(self, id: int, result_name: str):
        self.id = id
        self.result = Result(result_name)


class Result:
    def __init__(self, name: str):
        self.name = name

object1 = MyObject(1, 'A')
object2 = MyObject(2, 'A')
object3 = MyObject(3, 'B')
object4 = MyObject(4, 'B')

x_ids = (object1, object2, object3, object4)

Now we perform the list comprehension:

from functools import reduce
result = tuple(reduce(lambda t, s: {**t, s.result.name: s}, x_ids, {}).values())

Result:

(object2, object4)

The list comprehension (reduce) starts with an empty dict {}. Each iteration, an entry from x_ids is passed to the lambda function as s and the current state of the dict is passed as t. The dict gets updated by adding the object s with key s.result.name. If that key already exists, the entry will be overwritten - this filters out objects with the same result name. The result is a dict: {'A':object2, 'B':object4}. The result is then converted into the required tuple format.

Top answer
1 of 4
7

I would use a list comprehension:

contexts_to_display = ...
tasks = [t for t in Task.objects.all()
         if t.matches_contexts(contexts_to_display)
         if not t.is_future()]
tasks.sort(cmp=Task.compare_by_due_date)

Since you already have a list, I see no reason not to sort it directly, and that simplifies the code a bit.

The cmp keyword parameter is more of a reminder that this is 2.x code and will need to be changed to use a key in 3.x (but you can start using a key now, too):

import operator
tasks.sort(key=operator.attrgetter("due_date"))
# or
tasks.sort(key=lambda t: t.due_date)

You can combine the comprehension and sort, but this is probably less readable:

tasks = sorted((t for t in Task.objects.all()
                if t.matches_contexts(contexts_to_display)
                if not t.is_future()),
               cmp=Task.compare_by_due_date)
2 of 4
3

Since you are writing Django code, you don't need lambdas at all (explanation below). In other Python code, you might want to use list comprehensions, as other commenters have mentioned. lambdas are a powerful concept, but they are extremely crippled in Python, so you are better off with loops and comprehensions.

Now to the Django corrections.

tasks = Task.objects.all()

tasks is a QuerySet. QuerySets are lazy-evaluated, i.e. the actual SQL to the database is deferred to the latest possible time. Since you are using lambdas, you actually force Django to do an expensive SELECT * FROM ... and filter everything manually and in-memory, instead of letting the database do its work.

contexts_to_display = ...

If those contexts are Django model instances, then you can be more efficient with the queries and fields instead of separate methods:

# tasks = Task.objects.all()
# tasks = filter(lambda t: t.matches_contexts(contexts_to_display), tasks)    
# tasks = filter(lambda t: not t.is_future(), tasks)
# tasks = sorted(tasks, Task.compare_by_due_date)
qs = Task.objects.filter(contexts__in=contexts_to_display, date__gt=datetime.date.today()).order_by(due_date)
tasks = list(qs)

The last line will cause Django to actually evaluate the QuerySet and thus send the SQL to the database. Therefore you might as well want to return qs instead of tasks and iterate over it in your template.

🌐
Finxter
blog.finxter.com › home › learn python blog › how to filter a list in python?
How to Filter a List in Python? - Be on the Right Side of Change
July 14, 2022 - In Python, each element has an associated Boolean value so you can use any Python object as a condition. The value None is associated with Boolean value False. Problem: Say, you’ve got a JSON list object. You want to filter the list based on an attribute.
🌐
Palantir Developer Community
community.palantir.com › ask the community
Filtering object sets in a Python function - Ask the Community - Palantir Developer Community
October 20, 2024 - I have an object in my ontology (obj_foo) that i want to filter. I have an array all_ui and want to check if the object property foo_array contains any value in the array all_ui. then, i want to apply all_filters to obj_foo but the filter() method does not exist on the object. here is my current approach: filter_condition = [obj_foo.foo_array.contains(ui) for ui in all_ui] all_filters = filter_condition[0] for condition in filter_condition[1:]: all_filters |= condition filtered...
🌐
Stack Overflow
stackoverflow.com › questions › 22947265 › filtering-a-list-of-objects-by-multiple-object-attributes
python - Filtering a List of Objects by multiple Object Attributes - Stack Overflow
July 9, 2016 - This does not remove the "older" object with matching name attribute (in this example, "DocumentA"). It simply returns the original query results. 2014-04-08T21:20:13.717Z+00:00 ... Oh yes, indeed. pass has to be continue of course. Edited answer, thanks! 2014-04-09T13:56:52.093Z+00:00 ... Provided your data meets the restrictions noted in the documentation, you should be able to use a projection query and group_by=["name"] and distinct=True to accomplish this.
🌐
Stack Overflow
stackoverflow.com › questions › 63317050 › python-filtering-a-list-of-custom-objects-by-one-of-its-dictionary-attributes
Python: filtering a list of custom objects, by one of its dictionary attributes - Stack Overflow
def parse_by(lst_cars, lst_category): c = lst_cars for item in lst_category: c = list(filter(lambda x: x.category[item] == 1, c)) return c ... This is a simply example of what you are probably looking for. There are for sure more efficient solutions, but this should help you for now. Note that I deleted the __ in front of your attributes to access them from outside with my function.
🌐
Enterprise DNA
blog.enterprisedna.co › python-filter-list-5-practical-methods-explained
Enterprise DNA: We Help Businesses Put Data and AI to Work
Learn data and AI skills on the platform, bring us in on a project, or run a managed Omni Command Centre. 220K+ professionals trained, 50+ production agents deployed.
🌐
HowToDoInJava
howtodoinjava.com › home › python › python list filter() with examples
Python List filter() with Examples
April 3, 2024 - In Python, we may need to filter a list to extract specific elements based on certain criteria or conditions. The filter() function is a powerful tool in Python that simplifies the process of filtering lists.
🌐
Stack Overflow
stackoverflow.com › questions › 26118631 › python-fast-filter-large-list-dict-of-objects-by-attribute-values
search - Python - fast filter large list/dict of objects by attribute values - Stack Overflow
May 23, 2017 - If you call that function in a loop, this will be faster than creating a list and looping over that list: #this is the generator ("yeld" makes the function a generator) def filterbyprice(seq, max_price): for el in seq: if seq[el].price <= max_price: yield el class Order(): def __init__(self, ord_id, price, status='open'): self.ord_id = ord_id self.price = price self.status = status orders = {'1':Order(1,12),'2':Order(1,9),'3':Order(1,1)} for cheap_order in filterbyprice(orders, 10): print cheap_order, orders[cheap_order], orders[cheap_order].price