PythonEnthusiast PythonEnthusiast - 5 months ago 8
Python Question

Do something every n iterations without using counter variable

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?

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

Use enumerate. Its built for this

Comments