352

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?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
greye
  • 8,921
  • 12
  • 41
  • 46
  • 1
    You might also be interested in the answers to iterating over a list in chunks: http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks – Dave Bacher Jul 01 '10 at 23:25

3 Answers3

769

The pythonic way is to use enumerate:

for idx, item in enumerate(my_list):
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Nick Bastin
  • 30,415
  • 7
  • 59
  • 78
122

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.

Vikram Garg
  • 1,329
  • 1
  • 8
  • 8
  • 14
    You could also use `enumerate`'s optional `start` parameter to start enumerating with 1 instead of 0, though then I'd use the OP's name `count` instead of `idx`. – Stefan Pochmann Oct 07 '17 at 12:36
3

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

Hans Ginzel
  • 8,192
  • 3
  • 24
  • 22