Check element exists in array

后端 未结 6 877
说谎
说谎 2021-01-30 08:23

In PHP there a function called isset() to check if something (like an array index) exists and has a value. How about Python?

I need to use this on arrays because I get \

6条回答
  •  南方客
    南方客 (楼主)
    2021-01-30 08:43

    Look before you leap (LBYL):

    if idx < len(array):
        array[idx]
    else:
        # handle this
    

    Easier to ask forgiveness than permission (EAFP):

    try:
        array[idx]
    except IndexError:
        # handle this
    

    In Python, EAFP seems to be the popular and preferred style. It is generally more reliable, and avoids an entire class of bugs (time of check vs. time of use). All other things being equal, the try/except version is recommended - don't see it as a "last resort".

    This excerpt is from the official docs linked above, endorsing using try/except for flow control:

    This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements.

提交回复
热议问题