list item's position

Mark McEahern marklists at mceahern.com
Thu Jan 20 04:29:50 CET 2005


Bob Smith wrote:

> Hi,
>
> I have a Python list. I can't figure out how to find an element's 
> numeric value (0,1,2,3...) in the list. Here's an example of what I'm 
> doing:

Use enumerate() (new in Python 2.3, IIRC).  Otherwise:

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

>
> for bar in bars:
>    if 'str_1' in bar and 'str_2' in bar:
>       print bar
>
> This finds the right bar, but not its list position. The reason I need 
> to find its value is so I can remove every element in the list before 
> it so that the bar I found somewhere in the list becomes element 0... 
> does that make sense?

Sure.  You want to slice the list starting at the index of the first 
occurrence:

index = min([i for i, item in enumerate(sequence) if 'str_1' in item and 
'str_2' in item])
print sequence[index:]

// m



More information about the Python-list mailing list