Skip to content Skip to sidebar Skip to footer

Index Out Of Range Error While Working With Lists In Python

I am writing a python code for my project purpose in which I want to implement windowing mechanism (surrounding words of a target word) and I have written following part for it wit

Solution 1:

You can use slicing for this:

defwindow(lst, index):
    return lst[max(0,index-2):index+3]

For example:

>>> foriinrange(10):
        print(i, window(list(range(10)), i))


0[0, 1, 2]1[0, 1, 2, 3]2[0, 1, 2, 3, 4]3[1, 2, 3, 4, 5]4[2, 3, 4, 5, 6]5[3, 4, 5, 6, 7]6[4, 5, 6, 7, 8]7[5, 6, 7, 8, 9]8[6, 7, 8, 9]9[7, 8, 9]

Slicing will "fail gracefully" if the upper index is out of bounds, returning as much as it can.

Solution 2:

Why not just use try/except mechanic?

defwindow_elements(win,ind,txt):
    for i in (1, 2, -1, -2):
        try:
            win.append(txt[index + i])
        except IndexError:
            passreturn win

Post a Comment for "Index Out Of Range Error While Working With Lists In Python"