Python – Default Counter Variable in For loop

Question:

Is there any default Counter Variable in For loop?

Asked By: Siva Arunachalam

||

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

Answered By: 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>
Answered By: Kathy Van Stone

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

Answered By: Sandro Munda
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.