Python list.index throws exception when index not found

前端 未结 10 1026
抹茶落季
抹茶落季 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:46
    def GetListIndex(list, searchString):
        try:
            return list.index(searchString)
    
        except ValueError:
            return False
    
        except Exception:
            raise
    
    0 讨论(0)
  • 2020-12-09 17:50

    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.

    0 讨论(0)
  • 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")
    0 讨论(0)
  • 2020-12-09 17:54

    One simple idea: -1 is perfectly usable as an index (as are other negative values).

    0 讨论(0)
提交回复
热议问题