Checking whether list element exists

Gary Herron gherron at islandtraining.com
Sat Apr 7 12:16:48 EDT 2007


Rehceb Rotkiv wrote:
> I want to check whether, for example, the element myList[-3] exists. So 
> far I did it like this:
>
> index = -3
> if len(myList) >= abs(index):
> 	print myList[index]
>
> Another idea I had was to (ab-?)use the try...except structure:
>
> index = -3
> try:
> 	print myList[index]
> except:
> 	print "Does not exist!"
>   
A try...except is a perfectly valid way to make the test.   However, the 
printing of the result is not necessary, and a "naked" except, as you 
have, is very dangerous programming practice.

That form of the except will catch ANY error and end up printing "Does 
not exist!", even errors that have nothing to do with what you're 
intending to test.

For instance, if you mistype the
  myList[index]
as
  myList[indx]
or
  mylist[indx]
an exception would be raised and caught by your except clause.

Or if you hit a keyboard control-c at exactly the right time, the 
resulting SystemExit exception would also be caught by your except clause.

A good programming practice would be to ALWAYS catch only the specific 
exception you want, and let any other's be reported as the errors they are:

try: 
  myList[index]
except IndexError:
  ...whatever...


Gary Herron

> Is it ok to use try...except for the test or is it bad coding style? Or 
> is there another, more elegant method than these two?
>
> Regards,
> Rehceb
>   




More information about the Python-list mailing list