Out of range index error when working with lists in python

I am writing python code for my project goal in which I want to implement a window mechanism (surrounding words of a target word), and I wrote the next part for it with the axample lists below. I get an “Out of Range Index” when the target word is not surrounded by at least two words on both sides.

Window = list()
text = ['dog','bark','tree']
polysemy = ['dog','bark','tree']

def window_elements(win,ind,txt):
    win.append(txt[index + 1])
    win.append(txt[index + 2])
    win.append(txt[index - 1])
    win.append(txt[index - 2])
    return win
for w in polysemy:
    window = list()
    index = text.index(w)
    window = window_elements(window,index,text)

Suppose that for the first run for the loop, the target word is “dog,” so from the window_element function I need a list of words 2 on the right side of “dog” and 2 on the left side of “dog”. But there are no words on the left side of the dog, so the list will not contain anything, and it will take only two words on the right side and correctly execute.
I want this mechanism, but I can not do it above. Can someone suggest me an additional mechanism that will fulfill my requirement?

0
source share
3 answers

You can try the following function. It will work fine.

def window_elements(win,ind,txt):
if(len(txt) == 1):
    return
elif(ind == 0 and len(txt) == 2):
    win.append(txt[1])
elif(ind == 1 and len(txt) == 2):
    win.append(txt[0])
elif(ind == 0):
    win.append(txt[index + 1])
    win.append(txt[index + 2])
elif(ind == (len(txt) - 1)):
    win.append(txt[index - 1])
    win.append(txt[index - 2])
elif(ind == 1 and len(txt) < 4):
    win.append(txt[index - 1])
    win.append(txt[index + 1])
elif(ind == (len(txt) - 2) and len(txt) >= 4):
    win.append(txt[index + 1])
    win.append(txt[index - 1])
    win.append(txt[index - 2])
elif(ind >= 2 or ind <= (len(txt) - 3)):
    win.append(txt[index + 1])
    win.append(txt[index + 2])
    win.append(txt[index - 1])
    win.append(txt[index - 2])
return win
+1
source

You can use slicing for this:

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

For instance:

>>> for i in range(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]

" ", , .

+3

Why not just use try / except mechanic?

def window_elements(win,ind,txt):
    for i in (1, 2, -1, -2):
        try:
            win.append(txt[index + i])
        except IndexError:
            pass
    return win
+1
source

Source: https://habr.com/ru/post/1529815/


All Articles