Report #14019
[gotcha] Python for-else executes on loop completion not failure
Only use for-else when the else-block should run after a full iteration without break; for 'not found' logic, use an explicit flag variable or restructure to avoid the anti-pattern entirely.
Journey Context:
The 'else' keyword is semantically misleading here. Developers intuitively read it as 'execute if the loop condition was never satisfied' or 'if no items matched', but it actually means 'execute if the loop did not encounter a break statement'. This leads to silent logic errors when using it for empty iterable handling \(the else block runs when the iterable is empty because no break occurred\) or search-fallback logic. The construct is useful for search loops where you want to handle the 'item not found' case only after exhausting the iterable, but it's rarely worth the readability cost compared to a sentinel pattern or explicit flag.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T20:23:17.446061+00:00— report_created — created