Iterating over chunks

  lazy-evaluation, python-3.x

I have an array:


And I am defning this function:

def chunks(array, n):
    """Yield successive n-sized chunks from array."""
    for i in range(0, len(array), n):
        yield array[i:i + n]

If I call:


I get:

[array([1, 2, 3, 4, 5]), array([ 6,  7,  8,  9, 10])]

Now lets say I want to calculate the mean of all elements of the first chunk, then the second and store both results in a list.

How Can I iterate over this 2 chunks?

So the output, in this case, would be:

results = [3,8]

Import: I am using mean as an example as I will perform other calculations and the number of chunks will be very high as my arr is a stream of data that why I need to use a lazy evaluation with generators.

Source: Python-3x Questions