list.index crashes when the element is not found

Larry Bates larry.bates at websafe.com`
Fri May 2 15:25:43 EDT 2008


TkNeo wrote:
> On May 2, 1:58 pm, Nick J Chackowsky <mediocre_per... at hotmail.com>
> wrote:
>> TkNeo wrote:
>>> WHAT ?
>>> This is crazy
>> Crazy like a fox?
>>
>> a = [1, 2, 3]
>> try:
>>      a.index(99)
>> except:
>>      a.append(99)
>> finally:
>>      print a.index(99)
>>
>> MY question: which exception should I actually be catching there?
>> ** Posted fromhttp://www.teranews.com**
> 
> ofcouse try catch is going to work but in ideality the index function
> should return a -1 and no way in hell crash.

-1 doesn't make any sense.  How could you tell the difference between the value 
being there and actually being -1 and it not being there and Python returning 
-1?  Raising an IndexError is the proper behavior.  You should catch the 
IndexError if you are going to be indexing into an list with arbitrary indexes.

-Larry



More information about the Python-list mailing list