Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find position of item in for loop over a sequence [duplicate]

Tags:

python

Possible Duplicate:
Accessing the index in Python for loops

list = [1,2,2,3,5,5,6,7]

for item in mylist:
    ...

How can I find the index of the item I am looking at, at some point in my loop? I can see there is a index() method for lists but it will always give me the first index of a value, so it won't work for lists with duplicate items

like image 862
Vaibhav Bajpai Avatar asked Jun 19 '11 17:06

Vaibhav Bajpai


2 Answers

Have a look at enumerate

>>> for i, season in enumerate('Spring Summer Fall Winter'.split(), start=1):
        print i, season
1 Spring
2 Summer
3 Fall
4 Winter
like image 133
Fredrik Pihl Avatar answered Sep 18 '22 15:09

Fredrik Pihl


Use an enumerator object:

for index, item in enumerate(mylist):
  ...
like image 32
bluepnume Avatar answered Sep 20 '22 15:09

bluepnume