7. Use next with a default for searches

Use next() with a generator expression when you want the first matching item.

This idiom captures a very common search pattern: first match or fallback. It keeps the success condition close to the iteration and avoids sentinel setup, break bookkeeping, and post-loop checks.

7.1. Don’t do this

1match = None
2for user in users:
3    if user.id == target_id:
4        match = user
5        break

7.2. Do this

1match = next((user for user in users if user.id == target_id), None)