Useless-Else-On-Loop
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.
Sourcery rule id: useless-else-on-loop
Section titled “Sourcery rule id: useless-else-on-loop”Description
Section titled “Description”Loop’s else clause is always executed - move code to same level as loop
Before
Section titled “Before”evens = []for n in numbers: if n % 2: evens.append(n)else: print("Done!")evens = []for n in numbers: if n % 2: evens.append(n)print("Done!")Explanation
Section titled “Explanation”Loops should only have an else clause if they can exit early with a break
statement. If there is no break then the code in the else is always
executed. In this case the else statements can be moved to the same scope as
the loop itself, making the code slightly easier to understand (no need to look
up what the else does).