list item's position

Stephen Thorne stephen.thorne at gmail.com
Thu Jan 20 01:06:48 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?

Given a list and a function:

def dropPredicate(x): 
  return not 'somecontents' in x

mylist = ['a', 'b', 'c', 'xxxxsomecontentsxxx', 'd', 'e', 'f']

import itertools

mylist = list(itertools.dropwhile(dropPredicate, mylist))

assert mylist == ['xxxxsomecontentsxxx', 'd', 'e', 'f']

This will drop everything at the start of the list for which
'dropPredicate' returns true. This will mean that even if
dropPredicate returns false for more than one element of the list, it
will stop at the first element. If there are no elements for which
dropPredicate returns true, the result will be an empty list.

Regards,
Stephen Thorne.



More information about the Python-list mailing list