Lafada Lafada - 4 months ago 8
Python Question

Checking and accessing array element without error

I have array, which I want to validate, 2nd item of that array. There are 2 ways which comes to my mind


  1. Check for
    array
    length

    if len(array) > 1:
    # Process for array[1]

  2. Catch
    IndexError
    and process in
    else
    block.

    try:
    array[1]
    except IndexError:
    pass
    else:
    # Process for array[1]



Which one is better?

If you have any other option, I am ready to learn :)

Answer

Python encourages EAFP coding style:

EAFP
Easier to ask for forgiveness than permission. 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. The technique contrasts with the LBYL style common to many other languages such as C.

This means the try / except is perfectly fine, but you do not have to use the else clause, simply do:

try:
    # Process for array[1]
except IndexError:
    pass
Comments