3

Is there any default Counter Variable in For loop?

Siva Arunachalam
  • 7,582
  • 15
  • 79
  • 132

3 Answers3

15

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.)

NPE
  • 486,780
  • 108
  • 951
  • 1,012
6

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>
Kathy Van Stone
  • 25,531
  • 3
  • 32
  • 40
5

Simple question, simple answer :

for (i, value) in enumerate(alist):
    print i, value

output :

1 value
2 value
3 value
...

where "value" is the current value of alist (a list or something else).

Sandro Munda
  • 39,921
  • 24
  • 98
  • 123