Get loop count inside a for-loop

PythonFor Loop

Python Problem Overview


This for loop iterates over all elements in a list:

for item in my_list:
    print item

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 my_list:
    print item
    count +=1
    if count % 10 == 0:
        print 'did ten'

Or:

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

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

Python Solutions


Solution 1 - Python

The pythonic way is to use enumerate:

for idx, item in enumerate(my_list):

Solution 2 - Python

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 - Python

Using zip function we can get both element and index.

countries = ['Pakistan','India','China','Russia','USA']

for index, element in zip(range(0,countries),countries):

         print('Index : ',index)
         print(' Element : ', element,'\n')

output : Index : 0 Element : Pakistan ...

See also :

Python.org

Solution 4 - Python

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])

Solution 5 - Python

This is something you can also do to check for the list index. When it hits the list index 9, which is the 10th element of the list, it will print "did ten".

for item in list:
    print item
    if list.index(item) == 9:
        print 'did ten'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongreyeView Question on Stackoverflow
Solution 1 - PythonNick BastinView Answer on Stackoverflow
Solution 2 - PythonVikram GargView Answer on Stackoverflow
Solution 3 - PythonMuhammad Faizan FareedView Answer on Stackoverflow
Solution 4 - PythonhephestosView Answer on Stackoverflow
Solution 5 - PythonVatsal DuttView Answer on Stackoverflow