Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)

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 make 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?

1 Answer

0 votes
by (106k points)

For getting loop count inside a Python for loop you can use the pythonic way is to use enumerate:

for idx,item in enumerate(list):

Related questions

0 votes
1 answer
asked Sep 23, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 8, 2019 in Python by Sammy (47.6k points)
+1 vote
2 answers
asked Aug 28, 2019 in Python by Sammy (47.6k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.6k users

Browse Categories

...