Checking whether list element exists

mensanator at aol.com mensanator at aol.com
Sat Apr 7 12:04:49 EDT 2007


On Apr 7, 10:52�am, Rehceb Rotkiv <reh... at no.spam.plz> wrote:
> > In general case it won't work, because lists accept negative indexes:
> >http://docs.python.org/lib/typesseq.html, 3rd note.
>
> Yes, I know! I _want_ the "3rd last list element", i.e. list[-3]. But it
> may be that the list does not have 3 elements. In this case, list[-3]
> will throw an error, cf.:
>
> >>> arr = ['a','b','c']
> >>> print arr[-3]
> a
> >>> print arr[-4]
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> IndexError: list index out of range
>
>
>
> I thought maybe I could catch the error with try...except so that I do
> not need the if-test, but I don't know whether this is proper usage of
> the try...except structure.

It's better than seeing if length>=abs(index).

>>> b = []
>>> index = 0
>>> if len(b)>=abs(index):
	print b[index]

Traceback (most recent call last):
  File "<pyshell#14>", line 2, in <module>
    print b[index]
IndexError: list index out of range
>>> try:
	print b[index]
except:
	print 'does not exist'

does not exist

The length test fails for an empty list but the
try/except method works when the list is empty.




More information about the Python-list mailing list