Skip to content
Sarj Code Standards

prefer-next-over-search-loop

Replace a first-match search loop with next() over a generator expression.

Why

A loop whose only job is to return the first matching item, followed by a fallback return, spreads one lookup over four statements. next() over a filtered generator states the search, the match condition and the fallback in one expression with the same laziness and short-circuiting.

Fix

Rewrite for item in items: if matches(item): return value(item) followed by return default as return next((value(item) for item in items if matches(item)), default). Keep the loop when the body grows side effects, logging or several exits.

Examples

Before — flagged A loop returns the first matching item with a fallback
service.py
def find_admin(users):
for user in users:
if user.is_admin:
return user
return None
After — preferred next() states the search and its fallback together
service.py
def find_admin(users):
return next((user for user in users if user.is_admin), None)