Open In App

How to Check End of For Loop in Python

Last Updated : 28 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, we often use loops to iterate over a collection like list or string. But sometimes, we may want to know when the loop has reached its end. There are different ways to check for the end of a for loop. Let's go through some simple methods to do this.

Using else with For Loop (Most Efficient)

The simplest way to check when a for loop has ended is by using the else clause. The else block after a for loop runs only when the loop has finished all iterations without being interrupted by a break statement.

Python
# Loop through numbers from 0 to 2 (range(3) generates 0, 1, 2)
for a in range(3):
    print(a)
else:
    print("End of loop")

Output
0
1
2
End of loop

Other techniques that give us different levels of control and flexibility depending on the needs of our code are:

Using enumerate() to Track Iteration

Sometimes we need to know the current index of the loop and also check if it's the last iteration. We can use the enumerate() function to get both the index and the value.

Python
for a, b in enumerate([10, 20, 30]):
  # Check if the current index 'a' is the last index (i.e., len(list) - 1)
    if a == len([10, 20, 30]) - 1:
        print("Last iteration")
    print(b)

Output
10
20
Last iteration
30

Using For Loop Counter

If we want even more control over the loop, we can use a counter to track iterations manually. Using For loop method is more complex but gives flexibility.

Python
a = [100, 200, 300]

#Assign '0' to Counter variable
counter = 0
for b in a:
  # Increment the counter by 1 for each iteration
    counter += 1
    if counter == len(a):
        print("End of loop")
    print(b)

Output
100
200
End of loop
300

Next Article
Article Tags :
Practice Tags :

Similar Reads