Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something every n iterations without using counter variable

Tags:

python

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?

like image 486
PythonEnthusiast Avatar asked Feb 19 '14 11:02

PythonEnthusiast


People also ask

How do you do iteration in Python?

You can create an iterator object by applying the iter() built-in function to an iterable. You can use an iterator to manually loop over the iterable it came from. A repeated passing of iterator to the built-in function next() returns successive items in the stream.

What is an iteration variable in Python?

The iterator (loop) variable is the variable which stores a portion of the iterable when the for loop is being executed. Each time the loop iterates, the value of the iterator variable will change to a different portion of the iterable.

What are the two types of iteration in Python?

There are two types of iteration: Definite iteration, in which the number of repetitions is specified explicitly in advance. Indefinite iteration, in which the code block executes until some condition is met.


2 Answers

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

Use enumerate. Its built for this

like image 163
Jakob Bowyer Avatar answered Sep 18 '22 15:09

Jakob Bowyer


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
like image 43
mdscruggs Avatar answered Sep 21 '22 15:09

mdscruggs