Checking whether list element exists

R

Rehceb Rotkiv

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
 
?

=?ISO-8859-2?Q?Wojciech_Mu=B3a?=

Rehceb said:
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]

IMHO it is good way.
Another idea I had was to (ab-?)use the try...except structure:

index = -3
try:
print myList[index]
except:
print "Does not exist!"

In general case it won't work, because lists accept negative indexes:
http://docs.python.org/lib/typesseq.html, 3rd note.

w.
 
R

Rehceb Rotkiv

In general case it won't work, because lists accept negative indexes:

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):

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.
 
M

mensanator

Rehceb said:
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]

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

In general case it won't work, because lists accept negative indexes:http://docs.python.org/lib/typesseq.html, 3rd note.

Why? What does negative indexes have to do with it?
print a[index]
except:
print 'does not exist'


does not exist
 
M

mensanator

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 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.
 
G

Gary Herron

Rehceb said:
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
 
T

Terry Reedy

|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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,190
Latest member
ClayE7480

Latest Threads

Top