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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.