Python - default counter variable in for loop

Is there any variable counter variable in a For loop?

+3
source share
3 answers

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

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

+13
source

Typically, if you iterate over a list (or any iterator) and want an index as well, use enumerate:

for i, val in enumerate(l):
   <do something>
+5
source

Simple question, simple answer:

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

conclusion:

1 value
2 value
3 value
...

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

+4
source

Source: https://habr.com/ru/post/1782459/


All Articles