Explain Codes LogoExplain Codes Logo

Why does python use 'else' after for and while loops?

python
loop-optimization
best-practices
python-idioms
Alex KataevbyAlex Kataev·Sep 6, 2024
TLDR

In Python, the else clause after loops fires off only if the loop concludes without hitting a break statement. This feature proves beneficial when there is a requirement to perform actions after the loop only when no early exit is triggered. Here's a snapshot:

for item in container: if item == target: # "target acquired" is the codeword break # mission accomplished, get out! else: print(f"{target} is playing hide and seek! Not found.")

In the scenario where target isn't located, the post-loop print statement within the else clause signals the target's absence.

When to employ 'else' in loops

Handling the 'what if' scenarios

The for...else mechanism manages situations where we didn't meet any desired condition during the iteration. Check this out:

for item in sequence: if item.passes_the_test: # Is this the Chosen One? process(item) # Let's roll! break else: print("No Chosen One here!")

The else clause here comes to play if the loop ran its course, but THE ONE remains elusive.

Flag variables dismissal

When it comes to avoiding flag variables, the 'else' clause after loops comes to our rescue, providing clean, neat code:

flag = False for item in container: if item == "pentagon": # They love their geometrics! flag = True break # Got'em, let's roll out! else: print("The hunt continues...")

Without our buddy else, we'd have to rope in further checks post-loop to address our 'not found' scenario.

Including 'no break' comments for clarity

Every story needs a good narrative. Including comments like # no break in your else clause makes it self-explanatory while aiding your fellow developers:

for x in data_pack: look_into(x) # Deep dive if x.is_queen_of_england(): # Pretty straightforward. I guess? break # off with the loop! else: # no break print("Nothing noble in here")

Behind 'else' in loops

Why 'else' and not a new keyword?

The Python Gods' choice to use else instead of introducing a fresh keyword adheres to a simple yet effective design decision: avoid keyword bloat while maintaining a sense of familiarity.

A historical tale and the logic structure

Noticed how Python's loops bare similarities with structured programming principles? Yeah, Donald Knuth had that figured out a long time ago. Loops use else to eliminate GOTO statements. Here, the raise statement directly linked to the loop completion manifests this tight coupling:

for record in records: if record.did_meet_the_queen(): # Important encounters only, please break # off with the searching! else: raise MissingRoyalEncounterError("You need to meet the queen!") # Brits might sympathise

The conditions are clear: each record must meet the queen, or we raise the red flag.

Considering performance

While we appreciate for...else, let's not ignore its performance considerations. Important code paths might benefit from faster list comprehensions or dedicated functions. Still, in its domain, else is the boss for enhancing readability and clarifying logic.

Insights from the wise

Raymond Hettinger, an experienced Python contributor, does an excellent job explaining the else clause in Python loops in his presentations. His perspectives and insights will offer tremendous value to the curious minds.

The community discussion

Did you ever wonder what the Python community thinks of else in loops? There's a whole thread dedicated to its discussion in the Python ideas thread.