Skip to content

Use Next

Sourcery refactoring id: use-next


Use the built-in function next instead of a for-loop.


def get_first_even_number(numbers):
    for number in numbers:
        if number % 2 == 0:
            return number
    return None


def get_first_even_number(numbers):
    return next((number for number in numbers if number % 2 == 0), None)


When choosing the first item from an iterable that passes a condition, we can use the next built-in function instead of a for-loop to make our code and our intent clearer.