Do something every n iterations without using a counter variable

I have an iterable list of over 100 items. I want to do something after every 10th iterative element. I do not want to use a counter variable. I am looking for some solution that does not include a counter variable.

I currently like this:

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

Is there a way in which I can omit the counter variable?

+8
python
source share
4 answers
 for count, element in enumerate(mylist, 1): # Start counting from 1 if count % 10 == 0: # do something 

Use enumerate . Its built for this

+22
source share

Just to show another option ... I hope I understood your question correctly ... slicing will give you exactly those list items that you want, without having to cycle through each item or store any enumerations or counters. See Python snippet notation notation .

If you want to start with the 1st element and get every 10th element from this 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 with the 10th element and get every 10th element from this point:

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

An example of the second 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 

Print

 10 20 30 ...etc... 100 
+5
source share
 for i in range(0,len(mylist)): if (i+1)%10==0: do something print i 
+1
source share

Another way to solve the problem is to break the iteration into your pieces before you start processing them.

grouper recipe does just that:

 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 as follows:

 >>> 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 just go to the by_twos list.

+1
source share

All Articles