problem:
listt= [2,0,5,4,2]
listt
has 4 lists of x=2
[2,0],[0,5],[5,4],[4,2]
listt
has 3 lists of x=3
[2,0,5],[0,5,4],[5,4,2]
problem:
listt= [2,0,5,4,2]
listt
has 4 lists of x=2
[2,0],[0,5],[5,4],[4,2]
listt
has 3 lists of x=3
[2,0,5],[0,5,4],[5,4,2]
You can use list-comprehension and take the subsequent slices
>>> listt= [2,0,5,4,2]
>>> n=2
>>> [listt[i:i+n] for i in range(len(listt)-n+1)]
[[2, 0], [0, 5], [5, 4], [4, 2]] # n=2
>>> n=3
>>> [listt[i:i+n] for i in range(len(listt)-n+1)]
[[2, 0, 5], [0, 5, 4], [5, 4, 2]] # n=3
Use a nested comprehension:
gen = (listt[i:i + n] for n in range(2, len(listt + 1)) for i in range(len(listt) - n + 1))
You can use the resulting generator, for example by printing it:
for sub in gen:
print(sub)
You may want to start n
at 1 rather than 2, since those are valid sublists too.