3 ms·
It always made sense to me since I think about these constructs as the loop searching for something (and breaking if it finds it) and the else running if nothin
by Doxin 8y ago
It always made sense to me since I think about these constructs as the loop searching for something (and breaking if it finds it) and the else running if nothing was found.
for item in list:
if search_condition:
found_item=item
break
else:
found_item=default_item
- hughdbrown 8y agoAs an alternative, you could do this: found_item = next((item for item in list if search_condition), default_item)