I have an issue with my python code and in some cases, users are getting the "IndexError: list index out of range" message. However, I'm not getting the error and it's not happening with every case so it's a bit confusing.

I did search the site and found this article that sort of addressed the problem but I wasn't able to make sense of it with my code.
http://www.daniweb.com/software-development/python/threads/354113

The error comes up at the first line on the following:

cd = context.sql.sql_enroll_location(myid = id_cookie)[0]
if(cd.company):
  flocation = cd.company
else:
  flocation = 'Not Selected'

Is there anything obvious that I'm doing wrong or could be improved? I have had issues with similar code and using the [0] or not as I have at the end of the first line.

Thank you for the help.

You might have an empty list, no data elements in it ...

mylist = []

print(mylist)       # []
print(len(mylist))  # 0

# empty list will give IndexError: list index out of range
print(mylist[0])

So should I change my code to something like:

cd = []
cd = context.sql.sql_enroll_location(myid = id_cookie)[0]
if(len(cd) > 0):
  flocation = cd.company
else:
  flocation = 'Not Selected'

In line 2, you're accessing index 0 of the list given by sql_enroll_location(). If that list is empty, that will trigger the index error. Save the list first, and then check its size. If it is not empty, then you can save the first element to the variable cd.

Edited 5 Years Ago by Mouche: n/a

You could do something like:

try:
    cd = context.sql.sql_enroll_location(myid = id_cookie)[0]
except IndexError:
    flocation = 'Not Selected'
else:
    flocation = cd.company
    
print(flocation)
Comments
that's it
This question has already been answered. Start a new discussion instead.