Skip to content

Use Next

Documentation Index

Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt

Use this file to discover all available pages before exploring further.

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.