Python – Default Counter Variable in For loop
Question:
Is there any default Counter Variable in For loop?
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.)
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>
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).
Is there any default Counter Variable in For loop?
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.)
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>
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).