Other than conditionals, what function/method to use to return an object that meets certain criteria in a list?

Question:

#COMPLETE BEGINNER
I’m trying to create a custom function in a class that offers a choice from a list based on 2 criteria. Due to my very limited knowledge, I can’t think of anything other than conditionals.
I want the function to return obj2 from objcollection in this case (criteria: c= "m" and d= "n")

class Blah:
    def __init__(self, a, b, c, d):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
    
obj1 = Blah("x", "t", "z", "f")
obj2 = Blah("g", "w", "m", "n")
objcollection = [obj1, obj2]
Asked By: S S

||

Answers:

Since you want to return an object based on a condition, using a conditional (e.g. an if) is definitely the right thing.

def select_cm_dn(objs):
    return next(o for o in objs if o.c == "m" and o.d == "n")

assert select_cm_dn(objcollection) == obj2
Answered By: Samwise
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.