Skip to main content

How to Check If a Loop Has Completed in Python

In Python, detecting whether a loop has finished normally (iterated through all items) versus being interrupted (by a break statement) is a common requirement. While flag variables are the traditional way to handle this in many languages, Python offers a unique and elegant else clause specifically for loops.

This guide explains how to track loop completion using boolean flags and the Pythonic for...else construct.

Method 1: Using a Flag Variable (Traditional)

The most universal way to check if a loop completed is to initialize a boolean variable (flag) before the loop, update it if a specific condition is met (like finding an item), and check it after the loop.

Example: Searching for a Value

numbers = [1, 3, 5, 7, 9]
target = 4
found = False # The flag

for num in numbers:
if num == target:
found = True
print(f"Found {target}!")
break # Exit loop early

# Check flag after loop
if not found:
print(f"{target} was not found in the list.")

Output:

4 was not found in the list.

This method is explicit and understood by programmers coming from languages like C++ or Java.

Method 2: Using the else Clause (Pythonic)

Python allows an else block to be attached directly to a for or while loop.

  • Executed: If the loop finishes naturally (exhausts the iterable).
  • Skipped: If the loop is terminated by a break statement.

This structure eliminates the need for the found flag variable in search logic.

Example: The "Search and Fallback" Pattern

numbers = [1, 3, 5, 7, 9]
target = 4

for num in numbers:
if num == target:
print(f"Found {target}!")
break # Skips the else block
else:
# This runs ONLY if the loop completed without breaking
print(f"{target} was not found in the list.")

Output:

4 was not found in the list.

Example: Successful Completion (Validating All Items)

You can use this to verify a condition holds for all items.

# Check if all numbers are odd
numbers = [1, 3, 5, 7]

for num in numbers:
if num % 2 == 0:
print(f"Found an even number: {num}")
break
else:
print("Loop completed: All numbers are odd!")

Output:

Loop completed: All numbers are odd!

Comparison and Best Practices

FeatureFlag Variablefor...else
ReadabilityHigh (Explicit logic)Medium (Can be confusing to beginners)
Code LengthVerboseConcise
Use CaseComplex logic, multiple break conditionsSimple search/validation logic

Best Practice: Use for...else when the logic is a simple "search and find" or "validate all" scenario. Use flags if the loop body is complex or if you need the status variable for logic later in the script.

Conclusion

To check if a loop has completed in Python:

  1. Use for...else for a concise, flag-free way to execute code only if the loop was not interrupted by break.
  2. Use a Boolean Flag if you prefer explicit logic or need to track the state beyond the immediate scope of the loop.