febreeze
febreeze

Reputation: 45

loop through a list and create arrays showing all sequences of n in a row, followed by the next iteration in the list

If I have a list, I'm attempting to create a function that will go through the list and create arrays of size n.

For example:

list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] with n = 3

Running the function would generate [0, 1, 2], [1, 2, 3], [2, 3, 4] etc.

Upvotes: 0

Views: 93

Answers (3)

N Chauhan
N Chauhan

Reputation: 3515

You can use zip with lists with incremented offsets:

lst = list(range(11))
n = 3
out = []
for sub in zip(*[lst[i:] for i in range(n)]):
    out.append(list(sub))

Since zip stops at the end of the final list, you won’t have any empty values at the end. And in a function:

def func(list, n):
    return [[*x] for x in zip(*[list[i:] for i in range(n)])]

Upvotes: 0

user6304394
user6304394

Reputation:

See if this works for you:

x=[0,1,2,3,4,5,6,7,8,9,10,11]

def lst(lst, n):
    for x in range(len(lst)-(n-1)):
        print(lst[x:x+n])

lst(x,3)

Output:

[0, 1, 2]
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 10]
[9, 10, 11]

Upvotes: 0

Mohsen_Fatemi
Mohsen_Fatemi

Reputation: 3401

If you want to write it as a function, you have two inputs:

input_list and n

Then you should iterate over the list, and make sub-lists with length n, i've done this using list slices.

def print_list(input_list,n):
    for i in range(len(input_list)):
        if len(input_list[i:i+n])==n:
            print(input_list[i:i+n])

Here you can find the output of this program with an example :

>>> print_list([1,2,3,4,5,6],3)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]

Upvotes: 0

Related Questions