Skip to content

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.

Loop’s else clause is always executed - move code to same level as loop

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!")

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).