rfaenger rfaenger - 23 days ago 6
Python Question

If Loop - Index out of range

this is the code

for i in np.arange(len(tupel)):
if tupel[i][0]+1 == tupel[i+1][0] and tupel[i][1] != 0:
pre.append((tupel[i][1]))
else:
means.append(pre)
pre = []


pre and means are just two lists. I have another list: "tupel". It looks something like

[(0, 10), (1, 16), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0), (8, 11), (9, 18), (10, 4), (11, 0), (12, 0), (13, 0), (14, 0), (15, 0), (16, 0), (17, 0), (18, 12), (19, 16), (20, 1)]


All tupels where the 2nd element is zero should be cut off by " != 0" argument. As you can see, the non-zero values (2nd element) exists in some intervals. Now what I want to do is calculating the mean of the sum of the 2nd elements OF following items.

For e.g.

(0, 10), (1,16) have non-zero 2nd elements. I want the mean the mean of the 1st element and 2nd elements. Would be: (1, 26/2).

(2,0), (3,0) ,(4,0), .. should be cut off. Because the 2nd element is zero.
(8, 11), (9, 18), (10,4) should be: (27/3, 33/3).

To check if the following items where the 2nd element is non-zero are "next integers" i created the loop (code above). But I get the error:

IndexError: list index out of range


How can I check the following item in the list without exceeding the range of the index?

Thanks in advance.

Answer

Problem is [i+1] - you use index out of range. You need np.arange(len(tupel)-1)