position in a for loop?

Mark McEahern mark at mceahern.com
Wed Dec 31 00:52:36 EST 2003


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).

> I think I am working way too hard to try to determine this - there is
> probably a  very simple way to know?
> 
> Spam_locations=[]
> list=['linguine','Spam', 'clams', 'Spam', 'steak', 'onions', 'apples',
> 'Spam']
> for food in list:
>         if food='Spam':
>         Spam_location.append(## position in list ##)

Other minor points:

* Don't use list as a name--you clobber the builtin name "list".

* Your comparison probably should be if food == 'Spam' rather than an
assignment of 'Spam' to the name 'food', which is what one equals sign
(distinct from two) does.  Assignment vs. comparison.  An eternal
gotcha.

So that'd be:

hits = []
foodItems = ['linguine','Spam','clams','Spam','steak']
for i, item in enumerate(foodItems):
    if item == 'Spam':
        hits.append(i)

Pre-enumerate, you'd do something like:

for i in range(len(foodItems)):
    item = foodItems[i]
    ...

Cheers,

// m






More information about the Python-list mailing list