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
0

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

0

You should use the built-in function enumerate.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.