position in a for loop?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • EP

    position in a for loop?

    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','Spa m', 'clams', 'Spam', 'steak', 'onions', 'apples', 'Spam']
    for food in list:
    if food='Spam':
    Spam_location.a ppend(## position in list ##) ## but how do I
    back reference the position in the for loop?

    I am hoping to get:
    [color=blue][color=green][color=darkred]
    >>> Print Spam_locations[/color][/color][/color]
    [1,3,7]

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

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


    EP



  • wolf

    #2
    Re: position in a for loop?

    you may want to have a look @
    http://aspn.activestate.com/ASPN/Coo.../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

    Comment

    Working...