list index()

Jason tenax.raccoon at
Tue Sep 4 08:14:21 CEST 2007

On Aug 30, 1:27 am, Marc 'BlackJack' Rintsch <bj_... at> wrote:
> On Thu, 30 Aug 2007 17:09:36 +1000, Ben Finney wrote:
> > zzbba... at writes:
> >> What's with the index() function of lists throwing an exception on not
> >> found?
> > It's letting you know that the item isn't in the list. There's no
> > sensible return value from an "index" function in that condition.
> What about -1?  C programmers do this all the time.  :-)
> Ciao,
>         Marc 'BlackJack' Rintsch

As other people pointed out, C doesn't have exceptions, so a C
programmer must make an in/out parameter to indicate an error, or have
a special return value.  In Python, you're most often searching the
list for an object which is in the list, so the lack of the object is
an exceptional condition.  You can certain check with the "in"
operator beforehand to avoid the exception.  You may also subclass a
list and override the index method, or write a standalone function to
catch the exception and change its value.

The reason why the exception is more Pythonic is that the return value
is always a guaranteed good index into the list.  Any errors
(including calling .index() on a non-list instance that doesn't have
a .index method) are exceptional, and should probably follow a very
different code path.

Returning -1 is not a good return value to indicate an error.  After
all, -1 is a valid index in most Python lists.  (Negative numbers
index from the tail of the list.)


More information about the Python-list mailing list