list item's position

Bengt Richter bokr at oz.net
Thu Jan 20 04:59:29 EST 2005


On Wed, 19 Jan 2005 22:04:44 -0500, Bob Smith <bob_smith_17280 at hotmail.com> 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:
>
>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?
>
sneaky (python 2.4) one-liner (not tested beyond what you see, and not recommended
as the best self-documenting version ;-)

 >>> bars = [
 ... 'zero',
 ... 'one',
 ... 'str_1 and str_2 both in line two',
 ... 'three',
 ... 'four',
 ... 'str_1 and str_2 both in line five',
 ... 'last line']

 >>> newbar=bars[sum(iter(('str_1' not in bar or 'str_2' not in bar for bar in bars).next, 0)):]
 >>> for s in newbar: print repr(s)
 ...
 'str_1 and str_2 both in line two'
 'three'
 'four'
 'str_1 and str_2 both in line five'
 'last line'

Alternatively:

 >>> newbar=bars[[i for i,v in enumerate(bars) if 'str_1' in v and 'str_2' in v][0]:]
 >>> for s in newbar: print repr(s)
 ...
 'str_1 and str_2 both in line two'
 'three'
 'four'
 'str_1 and str_2 both in line five'
 'last line'

Alternatively:

 >>> newbar = list(dropwhile(lambda x: 'str_1' not in x or 'str_2' not in x, bars))
 >>> for s in newbar: print repr(s)
 ...
 'str_1 and str_2 both in line two'
 'three'
 'four'
 'str_1 and str_2 both in line five'
 'last line'

Regards,
Bengt Richter



More information about the Python-list mailing list