Search code examples
pythonpython-3.xlistsliding-window

Sliding window with burn-in elements


I have a Python list. Here is an example:

seq = [0, 1, 2, 3, 4, 5]

Now I would like to iterate over the list with a window. For example, with a window of size 3 I can do it as follows:

window_size = 3
for i in range(len(seq) - window_size + 1):
    print(seq[i: i + window_size])

This would result in the following output:

[0, 1, 2]
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]

Now, I would like to also include the burn-in phase, i.e. lists with less than window_size elements. The output should be as follows:

[0]
[0, 1]
[0, 1, 2]
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]

How can my code be extended to do this most efficiently (also for bigger lists and bigger window_size)?


Solution

  • There are good answers already to this question, but just wanted to share another method using only 1 loop to do the same.

    window_size = 3
    arr = [0, 1, 2, 3, 4, 5]
    
    for x in range(1, len(arr)+1):
        if x < window_size:
            print(arr[:x])
        
        else:
            print(arr[x-window_size:x])
    

    Output:

    [0]
    [0, 1]
    [0, 1, 2]
    [1, 2, 3]
    [2, 3, 4]
    [3, 4, 5]