Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a list comprehension for returning first found element or None

I want to optimize my python code and I thougt I could improve the following for loop with a list comprehension to increase performance:

for obj in self.objs:
    if obj.is_runnable():
        return obj
return None

My idea was to do something like this:

objs = [obj for obj in self.objs if obj.is_runnable()]
return objs[0]

But I think this wouldn't be better, beacuse it does not stop iteration after the first found element and for now it doesn't handle the None case, but this could be avoided with an if-else statement.
My question: Is there a way, tou use a list comprehension, which breaks, after it returns the first element?

like image 382
RoQuOTriX Avatar asked Oct 22 '25 19:10

RoQuOTriX


1 Answers

Use next with a default value:

return next((obj for obj in self.objs if obj.is_runnable()), None)

Note that I changed the list comprehension [...] to a generator expression (...), otherwise you would still create the entire list before getting the first element. With (...), it will only test as many elements as needed.

Or with filter, where ClassOfObj is a placeholder for the class of obj:

return next(filter(ClassOfObj.is_runnable, self.objs), None)
like image 151
tobias_k Avatar answered Oct 24 '25 08:10

tobias_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!