Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Default Counter Variable in For loop

Tags:

python

Is there any default Counter Variable in For loop?

like image 480
Sivasubramaniam Arunachalam Avatar asked Nov 28 '22 22:11

Sivasubramaniam Arunachalam


2 Answers

No, you give it a name: for i in range(10): ...

If you want to iterate over elements of a collection in such a way that you get both the element and its index, the Pythonic way to do it is for i,v in enumerate(l): print i,v (where l is a list or any other object implementing the sequence protocol.)

like image 74
NPE Avatar answered Dec 06 '22 16:12

NPE


Generally, if you are looping through a list (or any iterator) and want the index as well, you use enumerate:

for i, val in enumerate(l):
   <do something>
like image 45
Kathy Van Stone Avatar answered Dec 06 '22 15:12

Kathy Van Stone