Home > Enterprise >  How to handle IndexError inside if statement without using try
How to handle IndexError inside if statement without using try

Time:07-19

I been having this problem in my code, that i solved and think the solution would help other people.

I have a list of objects and need to check if the objects variables are less, more, equal to other variables, the problem is that i don't always have a object in the list, so python would give an Index Error, because the list would be empty, i tried using try to catch the error but it made the code messy and hard to read.

To simplify, all i wanted was to say: if list[0].value < value2: do this, and if List Index does not exist or the condition is not True than go to else statement.

I will give the solution below and anyone else is free to give others solutions too

CodePudding user response:

The way that i found to do this was, when creating the list append values that are NAN, now the list has values to be checked and if the values are NAN the answer will always be False witch leads to going to else.

I actually was using objects, so i just created a new object with all variables set to NAN.

I used numpy.nan

CodePudding user response:

Couldnt you just check that the list length is greather than the index you want to check and then check the condition. Since and shortcircuts, if the list isnt long enough then the index will not get checked. this means you dont have to create dummy data especially for super long lists like in this case where i want to check index one million. This also saves you having to install and utilise other modules such as numpy

mylist = [1, 3]
index = 1_000_000
if len(mylist) > index and mylist[index] < 2:
    print("yay")
else:
    print("nay")
  • Related