Do something every n iterations without using counter variable

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

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

Use enumerate. Its built for this


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

Tags:

Python