Search code examples
pythonlistnumpymeanchunks

How to calculate mean of every three values of a list


I have a list:

first = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]

I want another list with mean of three values and so the new list be:

new = [2,5,8,11,14,17]

There will be only 6 values in the new list as there are only 18 elements in the first.

I am looking for an elegant way to do this with a minimal number of steps for a large list.


Solution

  • You can take a slice of first using for loop that iterates in 3 interval

    import statistics
    
    new = [statistics.mean(first[i:i + 3]) for i in range(0, len(first), 3)]
    print(new) # [2, 5, 8, 11, 14, 17]