Search code examples
python-3.xpython-itertools

How to reset a list and start populate it again using an iterator


I have the code below working.

What I need: After I get the two lists with 10 elements each my iterator still have 80 elements, so I need to repeat this process more 4 times but I want to reset both lists at each loop.

I dont want to create arr3, arr4...etc because the original array has more than 100000 elements.

How can I repeat this loop reseting the lists?

# creating an array with 100 samples
array = np.random.rand(100)

# making the array an iterator
iter_array = iter(array)

# List to store first 10 elements
arr1=[]


# List to store next 10 elements
arr2=[]

# First Iteration to get 2 list of 10 elements each
for _ in itertools.repeat(None, 10):
    a =next(iter_array)
    arr.append(a)
    b=next(iter_array)
    arr2.append(b)

Solution

  • You can store your result in a list-of_lists:

    import numpy as np
    import itertools
    
    # creating an array with 100 samples
    array = np.random.rand(100)
    
    # making the array an iterator
    iter_array = iter(array)
    
    # List to store first 10 elements
    n = 2
    result = [[] for _ in range(n)]
    
    # First Iteration to get 2 list of 10 elements each
    for _ in itertools.repeat(None, 10):
        for i in range(n):
            result[i].append(next(iter_array))
    
    print(f"{result = }")
    

    You can change the n-value to store 8 arrays or more.