How to find an item/items in a list?

Bengt Richter bokr at oz.net
Mon May 5 18:58:46 EDT 2003


On Mon, 5 May 2003 10:35:19 -0600, "Bjorn Pettersen" <BPettersen at NAREX.com> wrote:

>So, for some reasong I've been trying to find the "next" value (or all
>following values) after a certain "item" in a list. It's easy to do:
>
>  nextVals =3D lst[lst.index(item)+1:]
>
>but this can throw (which is a pain, especially when the algorithm
>naturally deal with an empty nextVals :-).
>
>Is there a better way of doing this? I was thinking perhaps a "value
>slice":
>
>  lst[slice(item)]
>
>but it seems like overkill. Perhaps:
>
>  lst.after(item)
>
>would be clearer? Or is this such a special operation, that I should
>just "move on" <wink>?
>
Don't know how much better, but you can prevent the exception with a
short circuit expression:

 >>> lst = list('abcdef')
 >>> item = 'c'
 >>> lst[lst.count(item) and lst.index(item)+1 or len(lst):]
 ['d', 'e', 'f']
 >>> item = 'x'
 >>> lst[lst.count(item) and lst.index(item)+1 or len(lst):]
 []
 >>> item = 'f'
 >>> lst[lst.count(item) and lst.index(item)+1 or len(lst):]
 []
 >>> item = 'a'
 >>> lst[lst.count(item) and lst.index(item)+1 or len(lst):]
 ['b', 'c', 'd', 'e', 'f']
 >>> item = 'e'
 >>> lst[lst.count(item) and lst.index(item)+1 or len(lst):]
 ['f']

Maybe list should have a find method like str, since counting to
one suffices for the logic.

Regards,
Bengt Richter




More information about the Python-list mailing list