3

If I have a for loop using a range like this:

for x in range(10):

then in order to get the count, it's just x. But say 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 besides specifying an integer count variable and incrementing it each run through, like this?

layer = [somedata]
count = 0
for row in layer:
    print count
    count += 1
nife552
  • 213
  • 1
  • 2
  • 8
  • 1
    possible duplicate of [Python - get position in list](http://stackoverflow.com/questions/364621/python-get-position-in-list) – Bill Lynch Oct 06 '14 at 22:29

2 Answers2

10

You can use enumerate. This will give you a count of every iteration and the value you're iterating.

Note: like range you can specify at what index to begin counting.

for count, row in enumerate(layer):
    print count
jramirez
  • 8,537
  • 7
  • 33
  • 46
3
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
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218