Skip to content

Python exit for loop early

  • by

If you want to exit a loop early in Python you can use break , just like in Java. It is used in conjunction with conditional statements (if-elif-else) to terminate the loop early if some condition is met.

Python exit for loop early

Simple example code.

for i in range(5):
    if i == 3:
        break
    print(i)
print('Exit for loop')

Output:

Python exit for loop early

If you want to start the next iteration of the loop early you use continue, again just as you would in Java.

for i in range(5):
    if i == 3:
        continue
    print(i)
print('Finished')

Python exits out of two loops

done = False
for x in xs:
    for y in ys:
        if bad:
            done = True
            break

    if done:
        break

If you need to exit the loop based on a certain condition, you can use an if statement with break:

for item in my_list:
    if condition(item):
        break
    # Your loop code here

Replace condition(item) with the condition you want to check. If the condition is satisfied, the loop will exit prematurely.

Note: Using break should be done judiciously, as it can make the code less readable and harder to maintain. Consider using other constructs like functions or list comprehensions if you find the need for early exits too frequently.

Comment if you have any doubts or suggestions on this Python loop topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading