New list made of the average of consecutive neighboring elements from a list

Viewed 19

What would be the best way to write a new list where the new list is based on (is the average of) several elements from the previous list? Is a regular for-loop the only solution?

For example, the average of each two consecutive elements,

a= [4,2,5,3,2]

Output:

a_ave=[3, 3.5, 4, 2.5]

(4+2)/2=3, (2+5)/2=3.5, etc.

1 Answers

I guess you can't avoid the O(N) complexity here, because you can't skip iterating. In terms of lesser lines of code, maybe something like this?

print([(a[index] + a[index + 1]) / 2 for index in range(len(a) - 1)])
Related