Python list.index throws exception when index not found

前端 未结 10 1028
抹茶落季
抹茶落季 2020-12-09 17:00

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

10条回答
  •  無奈伤痛
    2020-12-09 17:51

    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")

提交回复
热议问题