Is there any default Counter Variable in For loop?
Asked
Active
Viewed 1.6k times
3
-
What do you mean by "default"? Why do you need a counter variable? – Karl Knechtel Dec 28 '10 at 17:33
-
It's pretty unclear what you're asking, you should type more than a single sentence to a question. – Falmarri Dec 28 '10 at 22:35
3 Answers
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
-
2Minor nit - `l` can be anything that implements the sequence protocol, not just a list. – Nick Bastin Dec 28 '10 at 16:29
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
-
2i is zero-indexed, not 1-indexed. To have the output start at 1 use the 'start' keyword argument. – Adam Nelson Apr 15 '11 at 20:35