How to find an item/items in a list?

Bjorn Pettersen BPettersen at NAREX.com
Tue May 6 02:56:41 EDT 2003


> From: Bengt Richter [mailto:bokr at oz.net] 
> 
> 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 = lst[lst.index(item)+1:]
> >
> >but this can throw (which is a pain, especially when the algorithm
> >naturally deal with an empty nextVals :-).

[...]

> 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']
[...]

Ouch! Don't we have a one-liner page somewhere? <wink>

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

Nah, find has the ugly -1 return code when not finding anything, which
is just as much trouble as an exception :-) A split() method would be
better...

-- bjorn





More information about the Python-list mailing list