Python list.index throws exception when index not

2019-01-18 04:28发布

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?

10条回答
【Aperson】
2楼-- · 2019-01-18 04:51

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.

查看更多
甜甜的少女心
3楼-- · 2019-01-18 04:51

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.

查看更多
劫难
4楼-- · 2019-01-18 04:51
def GetListIndex(list, searchString):
    try:
        return list.index(searchString)

    except ValueError:
        return False

    except Exception:
        raise
查看更多
放荡不羁爱自由
5楼-- · 2019-01-18 04:57

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:

  • You've typically got lots of nested homogeneous processing (e.g. math or SQL)
  • You don't care about distinguishing error types
  • You don't care where the error occurred
  • The operations are pure functions, with no side effects.
  • Failure can be given a reasonable meaning at the higher level (e.g. "No rows matched")
查看更多
淡お忘
6楼-- · 2019-01-18 04:59

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:

idx = l.index(x) if x in l else None
查看更多
疯言疯语
7楼-- · 2019-01-18 05:05

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.

查看更多
登录 后发表回答