break in Python: leaving a loop early

break stops a loop the moment it has done its job: the remaining items are dropped and the program resumes right after it.
6 min read
Believemy logo

Definition

A loop has one stubborn habit: it goes all the way to the end. It walks through everything it is given, even when the answer showed up at the third item and the nine hundred thousand that follow are of no use at all. What is missing is a way to say "that is it, I have found it, stop here".

That is what break is for. This statement stops the enclosing loop straight away: items not yet visited are dropped, and the program resumes at the first line written after the loop.

The most common example is a file read that stops on an end marker.

PYTHON
for line in handle:
    if line.startswith("END"):
        break        # we leave the loop, the rest of the file is ignored
    process(line)

Two things change for whoever writes that code. The first is the time saved: the program stops working on data it has nothing left to do with. The second matters more in the long run: the line states out loud the condition that ends the walk, instead of leaving it to be guessed from a control variable tested ten lines higher up.


It only leaves one loop at a time

Then comes the question everyone meets at their first two-dimensional table: what happens when loops are nested? The answer often surprises. break leaves only the nearest loop, the one directly containing it, and nothing else.

PYTHON
for row in grid:
    for cell in row:
        if cell == target:
            break        # leaves the cell loop, not the row loop
    # ... and the walk carries on with the next row, as if nothing happened

The target is found, and yet the program keeps sweeping the whole grid. The final result is sometimes correct in spite of it, which makes the flaw even harder to spot: it shows up only as unexplained slowness, or as a variable overwritten one turn too late.

To leave both loops at once, three routes exist, and they are not equal. The most readable moves the double loop into a function and leaves it with return, which does quit everything in one go and hands back the value found along the way. A boolean flag set in the inner loop then read in the outer one also works, at the cost of one more variable to keep track of. Raising and catching an exception works too, but it bends an error mechanism into steering a perfectly ordinary walk: keep it for the cases where the other two do not fit.


Its relationship with the loop else

Once the early exit is in place, a new question arrives: how do you tell, afterwards, whether the loop stopped because it found something, or because it ran out of items without finding anything? The usual reflex is to set a boolean before the loop and read it back later.

Python offers something shorter. A loop can carry an else block, and that block runs only when no break was met, that is, when the walk went all the way through without being interrupted.

PYTHON
for product in catalogue:
    if product.reference == wanted:
        print("In stock")
        break
else:
    print("Unknown reference")   # reached only if no break happened

The pair forms the "search, and report if nothing was found" pattern with no intermediate variable at all. It has another merit: the two outcomes of the walk read one under the other, in the same place, instead of being separated by the body of the loop.

Warning

This else does not read like the one on an if. It does not mean "otherwise", it means "if the loop went all the way through". The nuance is expensive: remove the break from the loop and the block will run every single time, including when the search succeeded. No error will be raised, only the message on screen will be wrong.


The controlled infinite loop

One case remains where the stop condition cannot be written at the top of the loop: the one where it depends on something that does not exist yet when the loop starts. A keyboard entry through input, for instance. There is no way to know whether the answer is valid before asking for it.

Hence a pattern that rests entirely on break: the while True loop, whose condition is true forever and which stops only through an explicit exit written inside it.

PYTHON
while True:
    answer = input("Continue? (y/n) ")
    if answer in ("y", "n"):
        break                      # the only way out of the loop
    print("Answer not understood")

Writing the same thing with a condition up front would force the variable to be created before the loop and given an artificial value, picked only so the first turn happens at all. That value means nothing, and it ends up on screen the day a message repeats it. The break version says exactly what goes on: repeat until a valid answer arrives.

In exchange, a risk appears. If no execution path ever meets the break, the loop never stops and the program freezes, with no error and no message to explain it. The reflex to build when writing a while True is to check right away that every branch leads somewhere.

Good to know

The question comes up quickly: can a break go inside a list comprehension? No, the syntax does not allow it and there is no equivalent. A comprehension describes a complete transformation, not a walk that gets interrupted. As soon as an early stop is needed, go back to a loop written out in full, or reach for the takewhile function from the itertools module.


Frequently asked questions

Question

What is the difference between break and continue?

Both interrupt something, but not the same thing. break leaves the loop entirely: whatever was left to visit will never be seen. continue drops only the current turn and moves straight on to the next item. To choose between them, ask yourself whether the remaining items still hold any interest. If they do, it is continue; if they do not, it is break.

Question

Does break work inside an if?

It works there, but it does not act on it. break always targets the enclosing loop, never the if it is written in: leaving an if would make no sense anyway, a conditional block ends by itself at the close of its indentation. Placed in an if that sits in no loop at all, it raises a SyntaxError as the file is read, before the very first line runs.

Question

Should break be avoided for clean code?

That is an old debate inherited from other languages, where the single exit stood as a rule of style, and the Python answer is no. Leaving early avoids a pointless walk and states the intent more clearly than a stop condition made of three tests glued together. The one case worth pausing on is a long loop riddled with scattered exits: the problem is no longer the break, it is the loop, which would gain from being split up. The Python course works through these trade-offs on real code.

Related terms

Discover our python glossary

Browse the terms and definitions most commonly used in development with Python.

Share this article

Want to help us? Share this article on your networks or even better: on your site, in an article or in your newsletter.