Filter as short-circuit check

Download python eBook


filter (python 3.x) and ifilter (python 2.x) return a generator so they can be very handy when creating a short-circuit test like or or and:

Python 2.x2.0.1
 # not recommended in real use but keeps the example short:
from itertools import ifilter as filter
Python 2.x2.6.1
 from future_builtins import filter

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)

The next-function gives the next (in this case first) element of and is therefore the reason why it's short-circuit.


Contributors: 1
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook