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

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]

Using 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 ?

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

segment_length = 4

# List comprehension
result = [sum(numbers[i:i + segment_length]) / segment_length
          for i in range(len(numbers) - segment_length + 1)]

print("New list with averages:", 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]

Using 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 islice function and then apply the mean function directly on the new list to get the final result ?

from statistics import mean
from itertools import islice

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

segment_length = 4

# With islice and mean
segments = zip(*(islice(numbers, i, None) for i in range(segment_length)))
result = list(map(mean, segments))

print("New list with averages:", result)
Given list: [10, 12, 14, 16, 18, 20, 22, 24, 26]
New list with averages: [13, 15, 17, 19, 21, 23]

Comparison

Method Advantages Best For
sum() and range() Simple, readable, no imports Basic sliding window averages
islice() and mean() More functional, uses built-in statistics Complex statistical operations

Conclusion

Both methods effectively calculate sliding window averages. Use sum() with range() for simplicity, or islice() with mean() for more advanced statistical operations.

Updated on: 2026-03-15T18:17:28+05:30

402 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements