An elegant way to count the loop iterations in python 3

So far, when we had to count the number of iterations in a loop, we would have (at least most of us 🙂 ) done something similar to this.

list=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p']
cnt=0

for item in list:
    cnt+=1
    print(cnt)

    if cnt%5==0:
        print ('Multiples of 5')

This piece of code initializes a list of alphabets, iterates over the list and prints whenever the counter ( cnt variable) is a multiple of five.

But there is an elegant and more pythonic way to do this using ‘enumerate()’ function. Try this.


list=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p']

for count, item in enumerate(list):
    
    print (count)
    if count!=0 and count % 5 == 0:
        print ('Multiples of 5')

Leave a comment