position in a for loop?

E

EP

In fear of bringing down the quality of the list, I nevertheless will ask:


How I can tell where I am in a for loop?

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 ##) ## but how do I
back reference the position in the for loop?

I am hoping to get:
[1,3,7]

I was thinking the back reference might be something like:
Spam_location.append(list.__iter__())
But that gives me <listiterator object at 0x00DBE3B0> not a value (position)...

I promise to be smarter next year... any help?


EP
 
W

wolf

you may want to have a look @
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297,
where it is said that 'the interpreter creates a secret
name that only exists while the list is being built.
That name is (usually) "_[1]", and it refers to the bound
method "append" of the list.'. for your specific problem,
the enumerate() solution is probably all that you need;
for other cases (such as checking whether a certain value
is already a member of the list), this solution may come
in handy. for example, in order to get a non-repetitive
string with all the characters found in a given text, you
could say

print ''.join(
[ x
for x in 'my words are repetitive'
if x not in locals()['_[1]'].__self__ ] )

hope that helps,


_wolf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,174
Messages
2,570,940
Members
47,485
Latest member
Andrewayne909

Latest Threads

Top