Reputation: 1705
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.
Upvotes: 2
Views: 211
Reputation: 2491
FP-pythonic way:
x1 = [1.0, 2.0, 3.0, 4.0, 5.0]
x2 = map(lambda x, y: (x + y) / 2, x1, [0] + x1[:-1])
Upvotes: 0
Reputation: 2742
The most succinct way I can think of expressing this:
[(i + j)/2 for i, j in zip(xrange(400), xrange(1,400))]
Or, equivalently:
xs = range(400)
[(i + j)/2 for i, j in zip(xs, xs[1:])]
Obviously, in Python3, xrange
is obsolete, so there you could use range
instead. Also, in Python3, the default behavior of /
changes, so you'd have to use //
instead if you want integers.
Upvotes: 1
Reputation: 250891
A shorter and faster one-line solution using list comprehensions:
x1=range(0,400) #use xrange if on python 2.7
x2=[(x1[i]+x1[i+1])/2 for i in range(len(x1)) if i<len(x1)-1]
Upvotes: 1
Reputation: 208425
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:
n = len(x1)
x2 = []
i = 0
for i in range(n-1):
x2.append((x1[i]+x1[i+1])/2)
Note that I also decreased the range by one, otherwise x1[i+1]
will cause an IndexError.
Upvotes: 3