Checking whether list element exists

Rehceb Rotkiv rehceb at no.spam.plz
Sat Apr 7 11:24:50 EDT 2007


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!"

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