list.index crashes when the element is not found

Jerry Hill malaclypse2 at gmail.com
Fri May 2 15:17:20 EDT 2008


On Fri, May 2, 2008 at 3:04 PM, TkNeo <tarun.kap at gmail.com> wrote:
>  ofcouse try catch is going to work but in ideality the index function
>  should return a -1 and no way in hell crash.

It doesn't crash.  It raises an exception.  This is a pretty
fundamental concept of python programming.  If you intend to program
in python, then you're going to have to deal with it.

Besides, returning -1 is a bad idea.  Take a look at the following:

lst = [1, 2, 3]
pos = lst.index(99)
lst[pos] = 0
print lst

What do you expect the result to be?  If lst.index(99) returned -1,
then lst would be [1, 2, 0], because negative indexes of a list are
perfectly valid in python -- they just count from the end of the list.

-- 
Jerry



More information about the Python-list mailing list