2

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.

2
  • 3
    try x2.append((x1[i] + x1[i + 1]) / 2) Commented Jun 19, 2012 at 17:17
  • 1
    Try doing for i in range(n-1):. Commented Jun 19, 2012 at 17:18

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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]

2 Comments

Why use enumerate if you're not using x? ISTM the shorter listcomp way would be [(x+y)/2.0 for x,y in zip(x1, x1[1:])].
replaced enumerate with range, didn't used zip because this is what came to my mind when I was solving this.
1

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.

Comments

0

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])

1 Comment

Did you mean to use map here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.