Skip to main content

Be a Problem Solver

Efficiently Retrieving the First Matching Element with a Default Option

If you need to retrieve the first element from an iterator that matches a condition, with a default value like None if no match is found, you can store the result in a variable and use a loop to iterate through the elements.

numbers = [1, 2, 3]

first_even = None
for number in numbers:
    if number % 2 == 0:
        first_even = number
        break

Alternatively, you can use the next(iterator, default) function to achieve the same result more concisely. The default value will be returned if the iterator is exhausted.

first_even = next((number for number in numbers if number % 2 == 0), None)