Skip to content

Useless-Else-On-Loop

Sourcery rule id: useless-else-on-loop

Description

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

Before

evens = []
for n in numbers:
    if n % 2:
        evens.append(n)
else:
    print("Done!")

After

evens = []
for n in numbers:
    if n % 2:
        evens.append(n)
print("Done!")

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