Checking whether list element exists
Rehceb Rotkiv
rehceb at no.spam.plz
Sat Apr 7 11:52:22 EDT 2007
> 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.
More information about the Python-list
mailing list