If list index exists, do X

前端 未结 12 840
清酒与你
清酒与你 2020-12-02 11:41

In my program, user inputs number n, and then inputs n number of strings, which get stored in a list.

I need to code such that if a certain

12条回答
  •  遥遥无期
    2020-12-02 12:25

    Using the length of the list would be the fastest solution to check if an index exists:

    def index_exists(ls, i):
        return (0 <= i < len(ls)) or (-len(ls) <= i < 0)
    

    This also tests for negative indices, and most sequence types (Like ranges and strs) that have a length.

    If you need to access the item at that index afterwards anyways, it is easier to ask forgiveness than permission, and it is also faster and more Pythonic. Use try: except:.

    try:
        item = ls[i]
        # Do something with item
    except IndexError:
        # Do something without the item
    

    This would be as opposed to:

    if index_exists(ls, i):
        item = ls[i]
        # Do something with item
    else:
        # Do something without the item
    

提交回复
热议问题