mercredi 3 août 2016

Checking and accessing array element without error python

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 lenght

    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 :)

Aucun commentaire:

Enregistrer un commentaire