Python list.index throws exception when index not found

前端 未结 10 1089
抹茶落季
抹茶落季 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:27

    It's mainly to ensure that errors are caught as soon as possible. For example, consider the following:

    l = [1, 2, 3]
    x = l.index("foo")  #normally, this will raise an error
    l[x]  #However, if line 2 returned None, it would error here
    

    You'll notice that an error would get thrown at l[x] rather than at x = l.index("foo") if index were to return None. In this example, that's not really a big deal. But imagine that the third line is in some completely different place in a million-line program. This can lead to a bit of a debugging nightmare.

提交回复
热议问题