Filter as short-circuit check

suggest change

To 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents