Get loop count inside a Python FOR loop

In a Python for loop that iterates over a list we can write:

for item in list:
    print item

and it neatly goes through all the elements in the list. Is there a way to know within the loop how many times I've been looping so far? For instance, I want to take a list and after I've processed ten elements I want to do something with them.

The alternatives I thought about would be something like:

count=0
for item in list:
    print item
    count +=1
    if count % 10 == 0:
        print 'did ten'

Or:

for count in range(0,len(list)):
    print list[count]
    if count % 10 == 0:
        print 'did ten'

Is there a better way (just like the for item in list) to get the number of iterations so far?


Solution 1:

The pythonic way is to use enumerate:

for idx,item in enumerate(list):

Solution 2:

Agree with Nick. Here is more elaborated code.

#count=0
for idx, item in enumerate(list):
    print item
    #count +=1
    #if count % 10 == 0:
    if (idx+1) % 10 == 0:
        print 'did ten'

I have commented out the count variable in your code.

Solution 3:

I know rather old question but....came across looking other thing so I give my shot:

[each*2 for each in [1,2,3,4,5] if each % 10 == 0])