How to find an item/items in a list?

Bjorn Pettersen BPettersen at NAREX.com
Tue May 6 03:00:13 EDT 2003


> From: Batista, Facundo [mailto:FBatista at uniFON.com.ar] 
>
> #- 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 :-). 
> 
> 
> I don't understand why this doesn't like you (?). 
>         Facundo 

Because to be "correct" for my algorithm (i.e. not cluttering it up by
catching exceptions) I'd have to write a function like:

 def after(lst, item):
   try:
     # throws ValueError when not found,
     # TypeError if lst is a string and item is not
     index = lst.index(item) 
     # throws IndexError when out-of-range
     return lst[index+1:]
   except ValueError, IndexError: 
     # let TypeErrors through (too surprising).
     return []

-- bjorn





More information about the Python-list mailing list