# Average of each n-length consecutive segment in a Python list

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

We have a list containing only numbers. We plan to get the average of a set of sequential numbers from the list which keeps rolling from the first number to next number and then to next number and so on.

## Example

The below example simplifies the requirement of finding the average of each 4-length consecutive elements of the list.

Given list:
[10,12,14,16,18,20,22,24,26]

Average of every segment of 4 consecutive numbers:

[13.0, 15.0, 17.0, 19.0, 21.0, 23.0]

## With sum and range

We use the list comprehension approach to take the sum of the consecutive numbers by applying range to keep track of how many numbers we gathered. Then we keep dividing the sum with the segment length with the help of a loop. Finally the result is gathered into a new list.

## Example

Live Demo

listA = [10,12,14,16,18,20,22,24,26]
print("Given list:",listA)
seg = 4
# List comprehension
res = [sum(listA[m:m + seg])/seg
for m in range(len(listA) - seg + 1)]
print("new list with averages: ",res)

Running the above code gives us the following result −

Given list:
[10, 12, 14, 16, 18, 20, 22, 24, 26]
new list with averages:
[13.0, 15.0, 17.0, 19.0, 21.0, 23.0]

## With islice and mean

In this approach we take help of python modules which can calculate these values in a more direct way. We keep slicing the elements of the list in the given range using the isslice function and then apply the mean function directly on the new list to get the final result.

## Example

Live Demo

from statistics import mean
from itertools import islice

listA = [10,12,14,16,18,20,22,24,26]
print("Given list:",listA)

# With islice and mean
listB = zip(*(islice(listA, i, None) for i in range(4)))
res = list(map(mean, listB))

print("new list with averages: ",res)

## Output

Running the above code gives us the following result −

Given list:
[10, 12, 14, 16, 18, 20, 22, 24, 26]
new list with averages:
[13, 15, 17, 19, 21, 23]
Updated on 22-Jul-2020 07:53:06