Python for…else

Summary: in this tutorial, you’ll learn about the Python for...else statement and how to use it effectively.

Introduction to the Python for…else statement #

In Python, the for statement can have an optional else clause, which you may not be familiar with especially if you’re coming from other languages such as Java or C#.

The following shows the syntax of the for statement with the else clause:

for item in iterables:
    # Process item
    if condition:
        break  # Terminate the loop prematurely
else:
    # Executed if the loop completes without a breakCode language: PHP (php)

In this syntax:

  • Python will execute the else block only if the for loop iterates all items in the iterables without hitting a break statement.
  • If Python encounters a break statement, it’ll skip the else block entirely.
  • If the iterables has no items, Python executes the else block immediately.

Unlike the break statement, the continue statement does not end the loop prematurely. Therefore, the else block will execute if the loop completes normarlly.

The following flowchart illustrates logic of the for...else statement: