4 ms·
I find this pattern very much better expressed with functional programming: item = next((item for item in container if search_something(item)), None) if it
by blumomo 8y ago
I find this pattern very much better expressed with functional programming:
item = next((item for item in container if search_something(item)), None)
if item:
process(item)
else:
not_found_in_container()
instead of as suggested in the blog post:
for item in container:
if search_something(item):
# Found it!
process(item)
break
else:
# Didn't find anything..
not_found_in_container()
- gvx 8y agoYour suggestion contains bugs, though. To make it fully equivalent to the code in the blog post, it would need to be: sentinel = object() item = next((item for item in container if search_something(item)), sentinel) if item is not sentinel: process(item) else: not_found_in_container() ... because item could be None or another falsy value.