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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With