Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of consecutive pairs in a list including a sum of the last element with the first

I have a list of elements like [1,3,5,6,8,7]. I want a list of sums of two consecutive elements of the list in a way that the last element is also added with the first element of the list. I mean in the above case, I want this list: [4,8,11,14,15,8]

But when it comes to the addition of the last and the first element during for loop, index out of range occurs. Consider the following code:

List1 = [1,3,5,6,8,7]
List2 = [List1[i] + List1[i+1] for i in range (len(List1))]

print(List2)
like image 398
Adnan Akram Avatar asked Aug 02 '20 06:08

Adnan Akram


People also ask

How do you add two adjacent elements to a list in Python?

average = [(nums[i]+nums[i+1])/2 for i in range(len(nums)-1)] I'll leave you to disect it and I would suggest looking up Python array manipulation.


2 Answers

List2 = [List1[i] + List1[(i+1)%len(List1)] for i in range (len(List1))]
like image 100
M Z Avatar answered Sep 29 '22 12:09

M Z


[List1[i] + List1[(i+1) % len(List1)] for i in range(len(List1))]

or

[sum(tup) for tup in zip(List1, List1[1:] + [List1[0]])]

or

[x + y for x, y in zip(List1, List1[1:] + [List1[0]])]  
like image 42
Steven Rumbalski Avatar answered Sep 29 '22 12:09

Steven Rumbalski