Sobes.tech
Junior — Senior

Different approaches to speeding up the first match search function

livecode

Task condition

Suggest several methods to optimize the fetch_first_match function by using generators, Python's built-in features, and safe default value handling techniques.

def fetch_first_match(condition, items=None):
    if items is None:
        items = []
    matches = [elem for elem in items if condition(elem)]
    if matches:
        first = matches[0]
        return first
    return None

fetch_first_match(lambda x: x == 1, [2, 3, 4])