How to Count the Number of Iterations in a Python Loop?

Estimated read time 1 min read

You can count the number of iterations in a Python loop by using a counter variable that gets incremented with each iteration of the loop. Here’s an example using a for loop:

# Input list
my_list = [1, 2, 3, 4, 5]

# Initialize counter variable
iteration_count = 0

# Iterate through each element in the list
for item in my_list:
    # Increment iteration count
    iteration_count += 1

    # Perform some operation on the item
    print(f"Processing item: {item}")

# Print the iteration count
print(f"Number of iterations: {iteration_count}")

In this example, we first define an input list my_list with some elements. Then, we initialize a counter variable iteration_count to 0. Next, we use a for loop to iterate through each element in the list. Inside the loop, we increment the iteration_count variable by 1 with each iteration, effectively counting the number of iterations that occur. Finally, after the loop, we print the iteration count using a print() statement. This technique can be used to count the number of iterations in any type of loop in Python, including for loops, while loops, and nested loops.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply