list index()

Carsten Haese carsten at uniqsys.com
Thu Aug 30 13:50:16 CEST 2007


On Wed, 2007-08-29 at 23:44 -0700, zzbbaadd at aol.com wrote:
> What's with the index() function of lists throwing an exception on not
> found? Let's hope this is rectified in Python 3.

You're assuming that this behavior is a mistake. It's not, and
consequently, it won't be "rectified".

>  If nothing else, add
> a function that doesn't throw an exception. There are a million
> situations where you can have an item not be in a list and it is not
> an exception situation.

How could it not be an exception, in the plain English sense of the
word? Most certainly you're asking for the index because you want to do
something with the index. If the item is not found, you have no index,
so that's a special case that must be handled separately. There is no
logical difference between handling that special case in an except
clause versus handling it with an if-branch.

Is the Pythonic way

try:
    i = somelist.index(thing)
    # Do something with i
except IndexError:
    # Do something if thing not found

really that much worse than the theoretical alternative

i = somelist.index_that_returns_an_indicator(thing)
if i!=ThingNotFoundIndicator:
    # Do something with i
else:
    # Do something if thing not found

?

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list