0

I would like to iterate through a list and reference the iteration number that I'm on. I can do it with a simple counter, but is there a built in function for this?

List= list(range(0,6))
count = 0
for item in List:
    print "This is interation ", str(count)
    count += 1
user2242044
  • 7,943
  • 23
  • 91
  • 154

2 Answers2

6

Its what that enumerate is for !

enumerate(sequence, start=0)

Return an enumerate object. sequence must be a sequence, an iterator, or >some other object which supports iteration.

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

And in iteration you can do :

for index,element in enumerate(seasons):
     #do stuff
Community
  • 1
  • 1
Mazdak
  • 100,514
  • 17
  • 155
  • 179
0

You should use the built-in function enumerate.

orlp
  • 106,415
  • 33
  • 201
  • 300