'How to avoid 'IndexError: list index out of range' error?

Suppose there are a list called 'my_list' and an int variable called 'list_index'. Basically, the list 'my_list' might change over time and hence the 'list_index' might raise 'IndexError: list index out of range'. However, I just want to make record when this error occurs since it is not that important. To avoid this error, my basic solutions currently are:

# My first way
if my_list[list_index: list_index +1]: 
    print('item exists')
else:
    print('item does not exist')

# My second way
if -len(my_list) <= list_index < len(my_list):
    print('item exists')
else:
    print('item does not exist')

Except for try/except statement, are there other solutions to avoid the 'IndexError: list index out of range' error?



Solution 1:[1]

You can use a try-except.

a = [1,2,3]

try:
 print(a[4])
except IndexError:
 pass

Solution 2:[2]

What we can do in this scenario is we know a possible error can happen, so we encapsulate the statements where the error is prone to happen inside try and we add an except block with an error type where we define what the program should do if it encounters that error.

The general syntax for it is,

try:
    # statements that can possibly cause an error
except error_type:
    # what to do if an error occurred

So here the error you are mentioning is IndexError which catches the out of index exception in runtime. So a neat and pythonic way to do it is as follows.

try:
    index_value = my_list[list_index]
except IndexError:
    index_value = -1
    print('Item index does not exist')

Solution 3:[3]

Use range(len(LIST)-1):

for i in range(len(LIST)-1):
        if LIST[i] < LIST[i+1]:
            ... # you got an idea; no index error since range(len(LIST)-1)

Solution 4:[4]

actually you don't need to catch it, you need to avoid it by using following construction:

my_list = [1, 2, 3, 4]
for i in range(0, len(my_list)):
    print(my_list[i])

len(my_list) - will prevent you to access to item that doesn't exist

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Noone
Solution 4 Yevhen Dmytrenko