list.index crashes when the element is not found

Erik Max Francis max at alcyone.com
Sat May 3 17:14:23 EDT 2008


Jeff wrote:

> The generally used idiom for that is:
> 
> lst = ['a', 'b', 'c']
> if 'a' in lst:
>   foo = lst.index('a')

It's not a very good idiom, since it iterates over the list twice 
unnecessarily:  first, to see if the object is in the list; then, to 
find the index of that object.  That's pointless wasteful.

The Pythonic idiom is to catch the exception and then deal with it as 
desired.

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis



More information about the Python-list mailing list