Search code examples
pythonarrayssumelement

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


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

Solution

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