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
  • 8,803
  • 25
  • 97
  • 164

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
  • 105,000
  • 18
  • 159
  • 188
0

You should use the built-in function enumerate.

orlp
  • 112,504
  • 36
  • 218
  • 315