Skip to content

Use Next

Sourcery refactoring id: use-next

Description

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

Before

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

After

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

Explanation

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.