I am a very new in Python so please forgive me the basic question.
I have an array with 400 float elements, and I need to add the first term with the second and divide by two.
I was trying something like:
x1=[0,...,399]
n = len(x1)
x2 = []
i = 0
for i in range(0,n):
x2[i]=(x1[i]+x1[i+1])/2
But it gives me the error: IndexError: list assignment index out of range
Thank you in advance.
The problem here is that you cannot assign a value to an index in a list that is higher than the length of the list. Since you just want to keep adding items to the list, use the
list.append()method instead:Note that I also decreased the range by one, otherwise
x1[i+1]will cause an IndexError.