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 d
def GetListIndex(list, searchString):
try:
return list.index(searchString)
except ValueError:
return False
except Exception:
raise
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.
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:
One simple idea: -1
is perfectly usable as an index (as are other negative values).