Python : IndexError: tuple index out of range - python

In python i have this code
if record[0][1]:
the problem is.. when mysql does not return anything and thus..
record[0][1]
has no data..
this python code fails:
if record[0][1]:
IndexError: tuple index out of range
i simply want it to move on to the "else" statement or simply consider this if statement as .. invalid given that
record[0][1]
has no value. or data.. ( incoming stuff from mysql )

try:
if record[0][1]:
# Do stuff
except IndexError:
pass

You can use a try...except or use a short-circuiting check on outer tuple.
if len(record) > 0 and len(record[0]) > 1 and record[0][1]:

Related

Index out of range sometimes

I have the following code:
def right_rounding(min_vol):
try:
splitted = str(min_vol).split('.')
if float(splitted[0]) >= 1:
return 0
else:
return len(splitted[1])
except Exception as e:
print("Error code =",mt5.last_error())
print(e, 'error ', traceback.format_exc())
pass
It works right most of the time but sometimes it gives index out of range
index out of range
It's because splitted, which is of type str, is of length 1.
You can try printing the list splitted and you'll see that you have a list with just 1 element in it, and that would be min_vol.
When you split a string with some delimiter (in this case it is .), the returned value will be the string itself if the delimiter doesn't exist.
I am not sure what you're trying to achieve with that code, but the issue is that there is no splitting[1] because the list doesn't have an element in the 1st index.
If you want to access the last element of the list, you can enter -1 as the index and it will work.

IndexError: string index out of range Show in odoo-14.0

elif token[1] == 'in' and not (isinstance(token[2], Query) or token[2]):
Exception
IndexError: string index out of range
This usually happens when we forget to wrap our search parameters into a tuple inside the list, like so:
self.search(['field', '=', value])
While it should be:
self.search([('field', '=', value)])
Note the ( before 'field', and the ) after value.
It's not a Odoo error it's simply a Python error.
Your variable token is a string but by looking at your code token must be a list or tuple.

python : list index out of range error 1

I am trying to check if the array I'm returning is empty.
The code i'm trying is:
if (r.json()['negative'][0]['topic']) == "":
the error i'm getting is index out of range error.
I know that means there is nothing in the array, but my code is crashing because it's returning nothing.
Any Ideas?
You are trying to access first element from an empty array r.json()['negative'] which is causing your code to fail.
Check if "negative" key is not empty array after that you can check your condition.
if (r.json()['negative']:
if (r.json()['negative'][0]['topic']) == "":
Don’t put it all in a single line or you lose the ability to know what exactly is going on.
data = r.json()
if 'negative' not in data:
print('negative key is missing')
elif len(data['negative']) == 0:
print('no items in the negative list')
elif 'topic' not in data['negative'][0]:
print('topic is missing')
elif data['negative'][0]['topic'] == '':
print('topic is empty')
else:
# now you can access it safely
print(data['negative'][0]['topic'])
since you are going 3 deep into a set of dictionary in a list in a dictionary- you will almost certainly need to check the length of each container (or check that the key is in the dictionary) as suggested by others, or it is considered more pythonic by some to just capture the exception and move on :
try:
if (r.json()['negative'][0]['topic']) == "":
# do stuff
except IndexError:
# do other stuff
This is the It is better to ask forgiveness than to ask permission principle which is commonly used.

Python : is there an alternate to: "except IndexError:" something lighter?

If mysql has no output...
if record[0][0]:
will return an error
IndexError: tuple index out of range
the only solution i know to fix this issue is:
try:
if record[0][0]:
# Do stuff
except IndexError:
pass
but this looks like a very heavy wrapper script
only to find out if
record[0][0]
has no data. ( no value )
is there something lighter that can be done such as..
if record[0][0] = ""
?
UPDATE:
This is my MYSQL code:
a = _mysql.escape_string(a)
db=b()
db.query("select * from b where a='" + a + "' limit 1")
result = db.store_result()
record = result.fetch_row()
UPDATE:
turns out what worked is:
if record:
rather than
if record[0]:
or
if record[0][0]:
In the general case, if you want to check if an item exists in a list, just check that it exists. Exceptions are considered Pythonic code. Using another construct for access checking is likely to be less readable and suffer from performance problems.
However, if you're really interested in something else.. how about this?
>>> if record[0]:
... field = record[0][0]
This works because an empty list ([]) evaluates as False in an if statement.
>>> record = [[]]
>>> if record[0]: # returns an empty list, e.g. []
... field = record[0][0] # is not executed
A simpler alternative:
import MySQLdb
conn = MySQLdb.connect(passwd="sekret",db="foo")
cur = conn.cursor()
cur.execute("select * from b where a=%s limit 1", (a,))
for result in cur:
print(result)
Note the changes:
Use MySQLdb, not the underlying _mysql* API
Don't concatenate variables into SQL query strings, this will lead to SQL injection.
Iterate over the cursor to get the results
In Python, there is a way to get a default value from a dict but not from a list. E.g. in a dict:
x = mydict.get('key') # x will be None if there is no 'key'
(you can also provide a different default as a 2nd arg to get() method)
Now, it would be convenient to have something like that for lists. Getting an item from a list
is in some ways very similar to getting an item from a dict, but not exactly the same. Python
made a design decision to not have a similar method for lists.
Of course, you can make your own very easily. I sometimes use a function in my own library
called 'getitem', which returns a default arg; however it only looks up one level of a list,
because I feel multiple levels is too much of a corner case and it's probably worth using
an exception with multiple levels. But, for one level you can do:
def getitem(seq, index, default=None):
"""Get item from a `seq` at `index`, return default if index out of range."""
try : return seq[index]
except IndexError : return default
Note that there's a gotcha: you can't assume that getting None back means there is no
item, if your list may itself contain None values. Seems obvious but that's something
you have to remember.
You can easily extend this function to accept multiple indexes and handle multiple
levels of lists, but then you may ask: how do I know at which level there was an
IndexError?

how to set the value of len(list_name)...?

I have a list that might return null values, then I have to iterate through it...ex:
for iter_aeh in range(len(alert_event_history_rows)):
alert_event_history_rows is a list and it can be null, so I want to set len(alert_event_history_rows) = 1 if alert_event_history_rows is a list of null values(0 rows).
But I get following error:
SyntaxError: can't assign to function call
for record_ae in alert_event_rows:
if len(alert_event_history_rows) == 0:
len(alert_event_history_rows) = 1
for iter_aeh in range(len(alert_event_history_rows)):
How to set the value of len(alert_event_history_rows)...?
Don't. Just handle the case where your list is empty with logic:
if alert_event_history_rows:
for item in alert_event_history_rows:
# do something
else:
# alert_event_history_rows was an empty list..
# do something else
This is a syntax error indeed:
len(alert_event_history_rows) = 1
... because you cannot make an assignment to a function call on the left hand side. It must be a variable that can receive the value. If what you really want to do is reinitialize that list to a single element null list, then you might do:
alert_event_history_rows = [None]
This should fix your problem
for record_ae in alert_event_rows:
for iter_aeh in range(max(len(alert_event_history_rows), 1)):

Categories