Filter as short-circuit check
suggest changeTo find the first element that is smaller than 100:
car_shop = [('Toyota', 1000), ('rectangular tire', 80), ('Porsche', 5000)]
def find_something_smaller_than(name_value_tuple):
print('Check {0}, {1}$'.format(*name_value_tuple))
return name_value_tuple[1] < 100
next(filter(find_something_smaller_than, car_shop))
# Print: Check Toyota, 1000$
# Check rectangular tire, 80$
# Out: ('rectangular tire', 80)
next pulls values until the predicate returns a true one, so later elements are not checked. If nothing matches, next raises StopIteration.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents