473,395 Members | 1,623 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Checking whether list element exists

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
Apr 7 '07 #1
7 18629
Rehceb Rotkiv wrote:
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.
Apr 7 '07 #2
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.
Apr 7 '07 #3
On Apr 7, 10:37�am, Wojciech Mula
<wojciech_m...@poczta.null.onet.pl.invalidwrote:
Rehceb Rotkiv wrote:
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?
>>a = [1,2]
index = -3
try:
print a[index]
except:
print 'does not exist'
does not exist
>
w.

Apr 7 '07 #4
On Apr 7, 10:52�am, Rehceb Rotkiv <reh...@no.spam.plzwrote:
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.

Apr 7 '07 #5
Rehceb Rotkiv wrote:
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
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
Apr 7 '07 #6

"Rehceb Rotkiv" <re****@no.spam.plzwrote in message
news:pa*********************@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

Apr 7 '07 #7
Thanks for your many helpful tips!

Rehceb Rotkiv
Apr 7 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Lucifer | last post by:
Hi I have some code for checking for cookies, that sets a cookie on page1 and checks for it on page2. and its based on the code by MS: ...
21
by: scandal | last post by:
I am a javascript newbie working on a script that checks whether a "path" from one element in an array to another is "blocked." Currently, the script pushes an already processed cell index (hence...
4
by: ug26jhw | last post by:
Is there any way to determine whether an element in a document exists. I have some code like this where the variable i changes: if(document.getElementById('pref'+i).innerHTML... When it...
26
by: Army1987 | last post by:
Is this a good way to check wheter a file already exists? #include <stdio.h> #include <stdlib.h> int ask(const char *prompt); typedef char filename; int main(int argc, char *argv) { FILE...
2
by: causesdrowsiness | last post by:
Hi everyone. Sorry if this is the wrong group for this question, but since it is .NET and VB, I thought someone may be able to help me here or point me to the right group for this. I am...
13
by: darkslide | last post by:
Hi, I'm checking if a file exists with the following code; If System.IO.File.Exists("C:\test.txt") = True Then MsgBox("File Exists") Else MsgBox("File Does Not Exist") End If ...
4
gundarap
by: gundarap | last post by:
Hello all, I'm working on minidom. My goal is to see whether an element already exists in the xml file before adding. I was using getElementsByTagName() to check weather the element already exists....
11
by: rh0dium | last post by:
Hi all, I have a simple list to which I want to append another tuple if element 0 is not found anywhere in the list. element = ('/smsc/chp/aztec/padlib/5VT.Cat', '/smsc/chp/aztec/padlib',...
5
by: antar2 | last post by:
Hello, I am a beginner in Python and am not able to use a list element for regular expression, substitutions. list1 = list2 = Suppose that I want to substitute the vowels from list2 that...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.