Checking whether list element exists

Terry Reedy tjreedy at udel.edu
Sat Apr 7 13:40:24 EDT 2007


"Rehceb Rotkiv" <rehceb at no.spam.plz> wrote in message 
news:pan.2007.04.07.15.25.04 at no.spam.plz...
|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]
# Note that tabs gets lost in some newsreaders. Spaces are better for 
posting

A full test of the index, equivalent to the try below, is as follows:

n = len(myList)
if -n <= index < n  # same as <= n-1, but avoids subtraction

This works for empty lists also (-0 <= i < 0 is never true!).

| Another idea I had was to (ab-?)use the try...except structure:
|
| index = -3
| try:
| print myList[index]
| except:
| print "Does not exist!"

Follow Gary Herron's comment on this.

| Is it ok to use try...except for the test

Both idioms are acceptible.  Some people would chose based on whether they 
expect bad indexes to be a normal occurence or an exceptional occurrence. 
One rule-of-thumb division point is 10% frequency.  More expensive tests 
would push this higher.

Terry Jan Reedy






More information about the Python-list mailing list