position in a for loop?

sdd daniels at dsl-only.net
Wed Dec 31 10:21:29 EST 2003


Mark McEahern wrote:

> On Tue, 2003-12-30 at 23:30, EP wrote:
>>How I can tell where I am in a for loop?  
> Great question.  Use enumerate (new with Python 2.3, I believe).
>... So that'd be:
> 
> hits = []
> foodItems = ['linguine','Spam','clams','Spam','steak']
> for i, item in enumerate(foodItems):
>     if item == 'Spam':
>         hits.append(i)

or, to play along:
   foodItems = ['linguine','Spam','clams','Spam','steak']
   hits = [i for i,food in enumerate(foodItems) if food == 'Spam']

-Scott David Daniels
Scott.Daniels at Acm.Org




More information about the Python-list mailing list