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:

The else clause is useful in some cases if you know how to apply it effectively.

Python for…else example #

Suppose that you have a list of people, where each person is a dictionary that consists of name and age like this:

people = [{'name': 'John', 'age': 25},
        {'name': 'Jane', 'age': 22},
        {'name': 'Peter', 'age': 30},
        {'name': 'Jenifer', 'age': 28}]Code language: JavaScript (javascript)

And you want to search for a person by name.

If the list contains the person, you want to display the information of that person. Otherwise, you want to show a message saying that the name is not found.

To do it, you may come up with a program like this:

people = [{'name': 'John', 'age': 25},
        {'name': 'Jane', 'age': 22},
        {'name': 'Peter', 'age': 30},
        {'name': 'Jenifer', 'age': 28}]

name = 'Maria'

found = False
for person in people:
    if person['name'] == name:
        found = True
        print(person)
        break

if not found:
    print(f'{name} not found!')
Code language: PHP (php)

Try it

Output:

Maria not found!

How it works:

  • First, initialize a variable with the name of person to search for (Maria).
  • Then, set a flag (found) to False. If the input name matches with a person on the list, set its value to True, show the person’s information and exit the loop by using the break statement.
  • Finally, check the found flag and show a message.

However, if you use the for else statement, the program will be much shorter.

The following shows the new version of the program that uses the for else statement:

people = [{'name': 'John', 'age': 25},
        {'name': 'Jane', 'age': 22},
        {'name': 'Peter', 'age': 30},
        {'name': 'Jenifer', 'age': 28}]

name = 'Maria'

for person in people:
    if person['name'] == name:
        print(person)
        break
else:
    print(f'{name} not found!')Code language: PHP (php)

Try it

By using the for else statement, the program doesn’t need to use a flag and an if statement after the loop.

In this new program, if the input name matches a person on the list, it’ll show the person’s information and exit the loop by using the break statement.

When the loop encounters the break statement, the else clause won’t execute.

Iterating over an empty list #

The following example uses a for...else statement to iterate over a list and display that the list is empty:

people  = []

for person in people:
    print(person)
else:
    print("The list is empty.")Code language: PHP (php)

Output:

The list is empty.Code language: PHP (php)

Summary #

  • Use Python for...else statement to execute a code block if the loop doesn’t encounter a break statement or if the iterables object is empty.

Quiz #

Was this tutorial helpful ?