how to sum elements among each other like arr[i] + arr[i+1] in python

Question:

I would like to create a function that sums first two elements and so on.
Like:

    arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

    result = [3, 5, 7, 9, 11, 13, 15, 17]

I did something like that but got no results

def Consec_Sum(arr):
    result = []
    for i in range(len(arr)-1):
        result = result.append(arr[i]+arr[i+1])
    return result
Asked By: aearslan

||

Answers:

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def Consec_Sum(arr):
    result = []
    for i in range(len(arr)-1):
        result.append(arr[i]+arr[i+1])
    print(result)

Consec_Sum(arr)

Result

[3, 5, 7, 9, 11, 13, 15, 17]

I didn’t analize the code. Just removed result =.

More similar to your code:

 arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]

 def Consec_Sum(arr):
     result = []
     for i in range(len(arr)-1):
         result.append(arr[i]+arr[i+1])
     return result

 print(Consec_Sum(arr))
Answered By: Novik
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.