Add current element in array + next element in array while iterating through array in Python
Question: What's the best way to add the first element in an array to the next element
in the same array, then add the result to the next element of the array, and
so on? For example, I have an array:

    
    
    s=[50, 1.2658, 1.2345, 1.2405, 1.2282, 1.2158, 100]
    

I would like the end array to look like the following:

    
    
    new_s=[50, 51.2658, 52.5003, 53.7408, 54.969, 56.1848, 100]
    

Thus leaving the minimum and maximum elements of the array unchanged.

I started going this route:

    
    
    arr_length=len(s)
    new_s=[50]
    
    for i, item in enumerate(s):
         if i == 0:
             new_s.append(new_s[i]+s[i+1])
         elif 0<i<=(arr_length-2):
             new_s.append(new_s[i]+s[i+1])
    

Currently I get the following list:

    
    
    new_s=[50, 51.2658, 52.5003, 53.7408, 54.969, 56.1848, 156.1848]
    

What am I doing wrong that isn't leaving the last item unchanged?


Answer: The beset way is using `numpy.cumsum()` for all of your items except the last
one then append the last one to the result of `cumsum()`:

    
    
    >>> import numpy as np
    >>> s=[50, 1.2658, 1.2345, 1.2405, 1.2282, 1.2158, 100]
    >>> 
    >>> np.append(np.cumsum(s[:-1]), s[-1])
    array([  50.    ,   51.2658,   52.5003,   53.7408,   54.969 ,   56.1848,
            100.    ])
    

Or with python (3.X) use `itertools.accumulate()`:

    
    
    >>> import itertools as it
    >>> 
    >>> list(it.accumulate(s[:-1])) + s[-1:]
    [50, 51.2658, 52.500299999999996, 53.74079999999999, 54.968999999999994, 56.184799999999996, 100]
    

