Abstract: Programming languages are just like any other cultural object: They stem from a specific historical context, they have shifted in meaning, and this affects decisions at a fundamental level. What was self-evident thirty years ago may elude even the best programmers today. While working on some analysis code, I stumbled upon one such decision. It is a feature of Python that allows for quick and easy checking whether one of several conditions has been met. It can produce cleaner and leaner code, but at the expense that the meaning of keywords used for it are not what you would expect.


Table of Contents

I am aware that many people know me for my rant about R code. And I stand by my words back then, because R has a few properties that make it less useful than it could be. However, for the most part, R is fine. It is like with any language — if you use it right, it will work just fine. I do have a rant on Python in planning, albeit I acknowledge that I still haven’t published it. But fret not, because today I stumbled upon a horrible, horrible part of Python that is the result of a complete whack decision, but that may come in extremely useful for many people. So I’m documenting this abomination of the language here to provide the warning label it should come with naturally. I’m talking about for-else constructions in Python.

For-Loops in Programming

To set the stage, consider what for-loops do. For-loops are intended to loop through a list of things and do something with them. For example, we may use them to loop through a list of lines of text:

for line in lines:
    print(line)

This is helpful if you’re working with text files, and you want to extract parts of the text based on information that can be determined on a line-by-line basis. Of course this example is not entirely contrived — I am currently working on a script to extract abstracts from scientific papers. Abstracts typically start with the heading “Abstract” on its own line, and thanks to the implicit standardization in scientific work, the end of the abstract can often be detected by checking for a line that reads “1. Introduction,” or “1. Motivation” etc. So it’s pretty easy to extract abstracts using an assortment of fixed expressions and regular expressions that match line by line.

However, despite the regularities in scientific papers, it typically does not suffice to have a single regular expression to cover all cases. In terms of coding ergonomics and transparency into what your code actually checks for, it makes sense to split up the detection work across multiple regular expressions. To give you my example, here is a list of various regular expressions that I have slowly accumulated that match varying types of abstract-ends based on the data I have:


end_regexp = [
  # RULE: many introductions start with 1. Some use I. (Roman literals)
  re.compile(r"^(?:1|I)\.\s"),
  # RULE sometimes we don't have a "1.", but rather the term "CONTENT"
  re.compile(r"^\s*CONTENT\s*$"),
  # RULE: sometimes we have "1 Introduction" (without the dot). INTRODUCTION can also be uppercase.
  # RULE: sometimes the first chapter is "Motivation"
  re.compile(r"^1\.?\s{1,}(?:introduction|motivation)", re.IGNORECASE),
  # RULE: sometimes, there are small chapters before the introduction, causing the intro to have 2.
  re.compile(r"[2-9]\s{1,}introduction", re.IGNORECASE),
  # RULE: sometimes we only have "Introduction" and then in a line thereafter a 1. (Again, case-insensitive)
  re.compile(r"^(?:Introduction|INTRODUCTION)")
]

The way you would check for these is then by using a nested for-loop:

for idx, line in enumerate(lines):
    for expression in end_regexp:
        if expression.match(line) is not None:
            end_line = idx
            break

What the code does is quite simple: Go through each line, and check if the line fulfills one of the criteria to be an “end” line of an abstract. If so, remember the index of that line to extract the abstract from start to finish afterwards, and then stop checking the rest. But there is a subtle bug in this code that I only discovered because I had a case where a paper would fail to yield an abstract even though the right expressions matched the right parts of the text individually.

Imagine that you have a paper where you have multiple lines that fulfill the starting or ending criteria for an abstract — nothing stops a paper from having multiple lines that look like “1. Introduction,” for example. Since I’m interested in the abstract, and the abstract is only at the beginning of a paper, the simplest heuristic here is to just take the very first line that matches and be done with it. However, the code above actually doesn’t stop. The break inside the inner for-loop will correctly break out of the inner for-loop, but it does not stop the outer for-loop. So the outer for-loop continues. If it detects another line that also fits one of the rules, it will silently overwrite the line with the higher index, until all lines have been checked. In short, instead of giving me always the first line that matches my conditions, it will always give me the last line that matches my conditions.

The simplest fix to this is, of course, to initialize the line indices with numbers that don’t describe lines and check if that has changed at some point, to then break out of the outer loop and stop checking lines:

end_line = -1 # The first index is 0, so -1 indicates "not yet found"
for idx, line in enumerate(lines):
    if end_line > -1:
        break # We have found the end-line in the previous run

    for expression in end_regexp:
        if expression.match(line) is not None:
            end_line = idx
            break

This would be a perfectly valid way to handle this case. However, I do try to use languages “correctly,” and if there is a feature that is intended for a very particular use-case, I try to use that one instead of other solutions. In the end, this is how we learn. So I started googling: “How do I break out of nested for-loops?” And the internet did not disappoint. There is a way to handle all of this neatly with one simple expression: for-else.

Failure Conditions of Loops and The For-Else Expression

This type of expression is not unique to Python. To understand what additional clauses after a for-loop could be, we need to understand the failure conditions that can occur within for-loops. When we write for-loops, it is almost always to check something, and there are three cases to consider:

  1. No special handling: We go through the for-loop and continue after the loop ends.
  2. We need to account for empty lists where the for-loop would never execute anything.
  3. We need to listen to a specific condition that happens inside the loop. This is the case we’re facing here.

First, to the default case where there is no special handling. Typically, for-loops in all languages are implemented in such a way that, if the list we want to go through is empty, we just don’t execute the statement block at all, and continue on with our day. This works for all kinds of for-loops that languages have been devising. Take a simple C for loop:

for (int i = 0; i < size; i++) {
    printf(i**2);
}

If size is 0, the print statement will never execute. What C (and many other languages) will do here is first initialize the index i to 0, and then check if i < size before doing anything else. If size is 0, then this check will be false the very first time, and as such the code will just jump to the end of the block, and continue running from there.

This works well for many languages, but for templating languages, this is not desirable, because the fact that some list is empty should be communicated to the user. Take a list of blog posts, which might be empty. To display a message to the visitor that there are no blog posts available, you could do a check of whether the post list is empty (using twig here):

{% if posts %}
{% for post in posts %}
<article>{{ post }}</article>
{% endfor %}
{% else %}
<p>No posts available</p>
{% endif %}

As you can see, it looks a bit awkward having to nest the for-loop inside an if-else expression to handle the empty-list case. Wouldn’t it be nicer to have this as a first-class feature of the language? That’s exactly what twig has done. You can use an else expression in a for-loop that will execute if the list is empty:

{% for post in posts %}
<article>{{ post }}</article>
{% else %}
<p>No posts available</p>
{% endfor %}

Neat! And it even makes sense semantically. What this construction essentially communicates is, “for every post in this list of posts, show the post contents, otherwise (‘else’), show the no-posts-available message.” One can argue about which one is the better way to handle this, but given the general context that a templating language should always output some message, it does not seem outlandish to have such a for-else contraption. What is important is that the two keywords essentially say “for some element in a list, do X, but if the list is empty, do Y.”

For-Else in Python

Returning to Python, it is often very common to use for-loops to check some condition and then break out of the loop if the condition has been met. Empty lists are so rarely a cause of concern that the language has no built-in way to handle this case (and, a simple check for if len(list) == 0 is trivial). But what is of concern is whether one of the elements inside that list meets some “stop” condition. And that’s what Python’s for-else contraption is for.

And it is a horrible war-crime, because it goes semantically against every intuition you may have. (There are historical reasons I explain below.) Essentially, if you add an else-condition to a for-loop, that else-condition will execute only, and only if no element in the for-loop triggered a break statement. In other words, it semantically says: “For every element in this list, do X. If nothing caused a ‘break,’ do Y.”

Let’s take the example from above, but this time with a for-else:

for idx, line in enumerate(lines):
    for expression in end_regexp:
        if expression.match(line) is not None:
            end_line = idx
            break
    else:
        continue
    break

What this code will do is the following:

  1. Go through every line
  2. For every line, go through every expression
  3. Check if that expression matches the line.
  4. If it does, remember the line and break out of the loop.
  5. If nothing triggered a break, continue with the outer loop.
  6. If we reach this point, the inner loop triggered a break, meaning we have found an end-line, so we can stop iterating through all the lines.

Essentially, this “links” the two breaks together — the outer break will execute only if the inner break has executed. And this is what just bends my mind, because the words on the screen do not match their meaning.

What does an “else” next to a for-loop communicate? Correct, it says “if something goes wrong with this loop, do this other thing.” What could we consider “something going wrong” in the context of a for-loop? Well, see above: either the list is empty, or something caused the loop to stop prematurely with a break. These are what I would consider “things that went wrong.”

However, what this else actually does is it executes either if the list is empty, or if the entire loop went through with no issues. The else statement correctly executes if the list is empty — as we would expect it. “Do X for every element in the list, but if it is empty, do Y.” So far so good. But the else will also execute if the loop just went through all elements of the list fine with no break statement.

Do you know when the else-statement will not execute? Correct: If something broke out of the loop. In other words, if something “went wrong.” To hammer home the oddity of this decision, take the following table:

Case Should an else-expression execute based on the meaning of the word “else”? Do template languages execute the else-expression? Does Python execute the else-expression?
The list contains elements and the for-loop went through it just fine. ❌ ❌ ✅
The list is empty and the for-loop never ran. ✅ ✅ ✅
The loop ended prematurely because something called break. ✅ (There is no break) ❌

In other words, Python will execute an else associated with a for-loop only if it has not encountered a break while running through the loop.

Historical Context: Why There is no For-Nobreak

Naturally, I was not the first to stumble over this footgun in the language. The internet is full of other articles of users who find this very odd. And in fact, many agree that a better name for this keyword would have been nobreak, because that would communicate exactly what happens: “If you don’t encounter any break while running through this loop, execute the code listed under nobreak.” In fact, that is such an obvious thing that it has been mentioned thirteen years ago by Raymond Hattinger in a lecture.

He explains the reasoning behind choosing else instead (from minute 16 in this recording). To summarize: the reason Python has else instead of nobreak is because the idea back then was that every break was only ever triggered by an if-clause, and the else clause after the for-loop was the correspondence to the many if-clauses that the loop would test.

However, there is an implicit assumption in this argument: Namely that a break would always be contained within an if-statement inside the loop. That would make the following code illogical:

for element in my_list:
    if some_condition(element):
        target_element = element
        continue
    break
else:
    print("No break encountered")
print("Loop ended.")

In this case, the else is not connected to an if, because, again, it gets triggered by a break statement and does not depend on the presence of an if-statement.

What is more, this syntax makes checking multiple lists awkward. In my code, I both check for regular expressions and fixed expressions (because a few select papers have clearly identifiable text to mark the end of abstracts). Writing “proper” “pythonic” code has caused the following Eldritch horror to appear:

for idx, line in enumerate(lines):
    # Check for a match of any end regex
    for r in end_regexp:
      if r.match(line) is not None:
        end_abstract = idx
        break
    else:
      # No regex matched. Check the fixed expressions
      for exc in end_fixed_expr:
        if line == exc:
          end_abstract = idx
          break
      else:
        # No luck with fixed expressions either, continue
        continue
      break

The issue here is easy to spot. As you have more lists of conditions to check, you slowly descend into what JavaScript users know as “callback hell.” So even if you buy into the “the else corresponds to the if inside the for-loop,” which, again, is not unreasonable, you cannot argue that this is healthy syntax, because it effectively breaks down after the first loop. If you have the situation where you only need to check for one list of conditions, this can be a valid construct. But remember that it requires mental effort to understand it, because the meaning of else is not the same as “else” in everyday usage in this context.

Final Thoughts

Where does this leave us? The pythonic version of “what if the loop didn’t break” clearly stems from more simple times. Today, especially with how coding languages have been evolving, the original intuition does not make sense anymore. We do not see for-loops as syntactic sugar for a bunch of goto-statements anymore. They are their own “thing” in our cultural conception.

In the end, after some deliberation (that is, after writing this article), I decided to move my code back to a more transparent layout:

end_abstract = -1
for idx, line in enumerate(lines):
    for r in end_regexp:
      if r.match(line) is not None:
        end_abstract = idx
        break

    if end_abstract > -1:
      break

    for exc in end_fixed_expr:
      if line == exc:
        end_abstract = idx
        break

    if end_abstract > -1:
      break

This may not be as “pythonic” as for-else and uses more code, but I decided that the benefits of having more transparent code outweigh the drawbacks. For a language that “almost reads like natural language,” the way for-else-loops work is just not acceptable. And this is just the latest example of numerous oddities that I really despise about Python. More to come in my rant.py article, which I now finally have new energy to finish.

Take that, snake! 🐍

Suggested Citation

Erz, Hendrik (2026). “for-else: A Python Footgun That Is Actually Helpful”. hendrik-erz.de, 27 Nov 2026, https://www.hendrik-erz.de/post/for-else-a-python-footgun-that-is-actually-helpful.

Never miss an article

Become a millennial in spirit and subscribe to this website's RSS feed. Simply copy and paste the link into your feed reader, and enjoy doomscrolling other people's thoughts instead of social media:
RSS Feed

For macOS and iOS, I recommend NetNewsWire (free and Open Source).

← Return to the post list