Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list.index throws exception when index not found

Tags:

Why does list.index throw an exception, instead of using an arbitrary value (for example, -1)? What's the idea behind this?

To me it looks cleaner to deal with special values, rather than exceptions.

EDIT: I didn't realize -1 is a potentially valid value. Nevertheless, why not something else? How about a value of None?

like image 764
Joan Venge Avatar asked Mar 23 '09 16:03

Joan Venge


People also ask

What happens if index is not found in Python?

The index() method searches for the first occurrence of the given item and returns its index. If specified item is not found, it raises 'ValueError' exception. The optional arguments start and end limit the search to a particular subsequence of the list.

What does index function return if not found?

index() function The index() method returns the index of a substring or char inside the string (if found). If the substring or char is not found, it raises an exception.


1 Answers

Because -1 is itself a valid index. It could use a different value, such as None, but that wouldn't be useful, which -1 can be in other situations (thus str.find()), and would amount simply to error-checking, which is exactly what exceptions are for.

like image 138
Devin Jeanpierre Avatar answered Oct 10 '22 20:10

Devin Jeanpierre