PythonEnthusiast PythonEnthusiast - 1 year ago 73
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 Source
for count, element in enumerate(mylist, 1): # Start counting from 1
    if count % 10 == 0:
        # do something

Use enumerate. Its built for this

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download