Open In App

Average of Each N-length Consecutive Segment in a List – Python

Last Updated : 18 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task is to compute the average of each n-length consecutive segment from a given list. For example, if the input list is [1, 2, 3, 4, 5, 6] and n = 2, the output should be [1.5, 2.5, 3.5, 4.5, 5.5]. Let’s discuss various ways in this can be achieved.

Using List Comprehension

This method uses list slicing within a list comprehension to calculate averages of consecutive segments.

Python
# Input list and segment length
a = [1, 2, 3, 4, 5, 6]
n = 2

# Calculate averages using list comprehension
res = [sum(a[i:i+n]) / n for i in range(len(a) - n + 1)]
print(res)  

Output
[1.5, 2.5, 3.5, 4.5, 5.5]

Explanation:

  • For each index in the range of valid segments, we slice a from i to i + n.
  • The sum of the sliced segment is divided by n to compute the average.
  • This method is simple and efficient for small to medium-sized lists.

Let’s explore some more methods and see how we can find average of each n length consecutive segments in a list.

Using Sliding Window with itertools

This approach uses the islice() function from itertools to create a sliding window and calculate averages.

Python
from itertools import islice

# Input list and segment length
a = [1, 2, 3, 4, 5, 6]
n = 2

# Create a sliding window and calculate averages
res = [(sum(islice(a, i, i+n))) / n for i in range(len(a) - n + 1)]
print(res)  

Output
[1.5, 2.5, 3.5, 4.5, 5.5]

Explanation:

  • islice(a, i, i + n) creates isslicea sliding window of size n from index i.
  • The sum of each window is divided by n to compute the average.
  • This method is slightly more efficient for larger lists because it avoids unnecessary slicing.

Using NumPy Convolution

This method employs NumPy’s convolution operation to calculate the averages.

Python
import numpy as np

# Input list and segment length
a = [1, 2, 3, 4, 5, 6]
n = 2

# Calculate averages using convolution
res = np.convolve(a, np.ones(n) / n, mode='valid')
print(res) 

Output
[1.5 2.5 3.5 4.5 5.5]

Explanation:

  • np.ones(n) / n creates a filter of size n where each element is 1/n.
  • The convolution operation slides this filter over the list a, computing the average for each segment.
  • NumPy operations are highly optimized for numerical computations and are efficient for large datasets.

Using for Loop

In this approach, we iterate through the list using a manual for loop to calculate segment averages.

Python
# Input list and segment length
a = [1, 2, 3, 4, 5, 6]
n = 2

# Initialize the result list
res = []

# Calculate averages manually
for i in range(len(a) - n + 1):
    segment = a[i:i+n]
    avg = sum(segment) / n
    res.append(avg)
print(res)  

Output
[1.5, 2.5, 3.5, 4.5, 5.5]

Explanation:

  • loop iterates through the indices of valid segments.
  • For each index, a slice is taken, and its average is computed and appended to the result list.

Using Pandas Rolling

This method uses the rolling function from pandas, which is ideal for handling rolling window operations.

Python
import pandas as pd

# Input list and segment length
a = [1, 2, 3, 4, 5, 6]
n = 2

# Create a pandas Series and calculate rolling averages
res = pd.Series(a).rolling(window=n).mean().dropna().tolist()
print(res) 

Output
[1.5, 2.5, 3.5, 4.5, 5.5]

Explanation:

  • The pandas rolling function computes the rolling average for a given window size.
  • .dropna() NaN values at the beginning, resulting from the initial incomplete window.
  • This method is highly efficient for large datasets but introduces an external library dependency.


Next Article
Practice Tags :

Similar Reads