Python list.index throws exception when index not found

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

    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
    

提交回复
热议问题