Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get loop count inside a Python FOR loop

In a Python for loop that iterates over a list we can write:

for item in list:     print item 

and it neatly goes through all the elements in the list. Is there a way to know within the loop how many times I've been looping so far? For instance, I want to take a list and after I've processed ten elements I want to do something with them.

The alternatives I thought about would be something like:

count=0 for item in list:     print item     count +=1     if count % 10 == 0:         print 'did ten' 

Or:

for count in range(0,len(list)):     print list[count]     if count % 10 == 0:         print 'did ten' 

Is there a better way (just like the for item in list) to get the number of iterations so far?

like image 899
greye Avatar asked Jul 01 '10 22:07

greye


People also ask

How do you count the number of items in a for loop in Python?

Using For Loop for loop is used to iterate over a sequence of values. To get the number of elements in the list, you'll iterate over the list and increment the counter variable during each iteration. Once the iteration is over, you'll return the count variable, which has the total number of elements in the list.

How do you count nested loops in Python?

To count statements in nested loops, one just separates the counts for the iterations of the outer loop, then adds them: count (nested loop) = count (1st iteration of the outer loop) + count (2nd iteration of the outer loop) + … + count (last iteration of the outer loop)

How do you do a loop count in Python?

Python's enumerate() lets you write Pythonic for loops when you need a count and the value from an iterable. The big advantage of enumerate() is that it returns a tuple with the counter and value, so you don't have to increment the counter yourself.


1 Answers

The pythonic way is to use enumerate:

for idx,item in enumerate(list): 
like image 98
Nick Bastin Avatar answered Sep 28 '22 20:09

Nick Bastin