Is there a way to get the loop counter of a for loop without using a range?
If I have a for loop using a range like this:
for x in range(10):
then it is just x to get the score. But tell me I have a for loop using a list:
layer = [somedata,someotherdata...etc]
for row in layer:
print #the number the loop is on
Is there a way to do this other than specifying an integer variable count and incrementing it each run like this?
layer = [somedata]
count = 0
for row in layer:
print count
count += 1
+3
nife552
source
to share
2 answers
You can use enumerate
. This will give you the count of each iteration and the value you iterate over.
Note: for example, range
you can specify at which index to start counting.
for count, row in enumerate(layer):
print count
+10
jramirez
source
to share
layer = ['a', 'b', 'c', 'd']
for index, value in enumerate(layer):
print 'Index: {} Value: {}'.format(index,value)
Output
Index: 0 Value: a
Index: 1 Value: b
Index: 2 Value: c
Index: 3 Value: d
+3
CoryKramer
source
to share