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)
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.
List2 = [List1[i] + List1[(i+1)%len(List1)] for i in range (len(List1))]
[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]])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With