17

I've an iterable list of over 100 elements. I want to do something after every 10th iterable element. I don't want to use a counter variable. I'm looking for some solution which does not includes a counter variable.

Currently I do like this:

count = 0
for i in range(0,len(mylist)):
    if count == 10:
        count = 0
        #do something
    print i
    count += 1

Is there some way in which I can omit counter variable?

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
Praful Bagai
  • 16,684
  • 50
  • 136
  • 267

5 Answers5

42
for count, element in enumerate(mylist, 1): # Start counting from 1
    if count % 10 == 0:
        # do something

Use enumerate. Its built for this

Guillaume Vincent
  • 13,355
  • 13
  • 76
  • 103
Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
12

Just to show another option...hopefully I understood your question correctly...slicing will give you exactly the elements of the list that you want without having to to loop through every element or keep any enumerations or counters. See Explain Python's slice notation.

If you want to start on the 1st element and get every 10th element from that point:

# 1st element, 11th element, 21st element, etc. (index 0, index 10, index 20, etc.)
for e in myList[::10]:
    <do something>

If you want to start on the 10th element and get every 10th element from that point:

# 10th element, 20th element, 30th element, etc. (index 9, index 19, index 29, etc.)
for e in myList[9::10]:
    <do something>

Example of the 2nd option (Python 2):

myList = range(1, 101)  # list(range(1, 101)) for Python 3 if you need a list

for e in myList[9::10]:
    print e  # print(e) for Python 3

Prints:

10
20
30
...etc...
100
Community
  • 1
  • 1
mdscruggs
  • 1,182
  • 7
  • 15
2
for i in range(0,len(mylist)):
    if (i+1)%10==0:
        do something
     print i
Avinash Garg
  • 1,374
  • 14
  • 18
2

A different way to approach the problem is to split the iterable into your chunks before you start processing them.

The grouper recipe does exactly this:

from itertools import izip_longest # needed for grouper

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

You would use it like this:

>>> i = [1,2,3,4,5,6,7,8]
>>> by_twos = list(grouper(i, 2))
>>> by_twos
[(1, 2), (3, 4), (5, 6), (7, 8)]

Now, simply loop over the by_twos list.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

You can use range loops to iterate through the length of mylist in multiples of 10 the following way:

for i in range(0,len(mylist), 10):
    #do something
jackw11111
  • 1,457
  • 1
  • 17
  • 34