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?
Because
-1
is itself a valid index. It could use a different value, such asNone
, but that wouldn't be useful, which-1
can be in other situations (thusstr.find()
), and would amount simply to error-checking, which is exactly what exceptions are for.To add to Devin's response: This is an old debate between special return values versus exceptions. Many programming gurus prefer an exception because on an exception, I get to see the whole stacktrace and immediate infer what is wrong.
I agree with Devin Jeanpierre, and would add that dealing with special values may look good in small example cases but (with a few notable exceptions, e.g. NaN in FPUs and Null in SQL) it doesn't scale nearly as well. The only time it works is where:
Well, the special value would actually have to be
None
, because -1 is a valid index (meaning the last element of a list).You can emulate this behavior by:
It's a semantic argument. If you want to know the index of an element, you are claiming that it already exists in the list. If you want to know whether or not it exists, you should use
in
.