Python get sublists
python
Solution
Use a loop and yield slices:
def get_sublists(length):
for i in range(len(lst) - length + 1)
yield lst[i:i + length]
or, if you must return a list:
def get_sublists(length):
return [lst[i:i + length] for i in range(len(lst) - length + 1)]
Problem
I've a very simple question about python and lists. I need to cycle trough a list and get sublists of a fixed lenght, spanning from the beginning to the end. To be more clear: ``` def get_sublists( length ): # sublist routine list = [ 1, 2, 3, 4, 5, 6, 7 ] sublist_len = 3 print get_sublists( sublist_len ) ``` this should return something like this: ``` [ 1, 2, 3 ] [ 2, 3, 4 ] [ 3, 4, 5 ] [ 4, 5, 6 ] [ 5, 6, 7 ] ``` Is there any simple and elegant approach to do this in python?