Skip to content

Useless else on loop

Sourcery refactoring id: useless-else-on-loop

Description:

Moves code in else blocks that is always executed to the main body

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