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]
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
  • Does this answer your question? [Iterate over all pairs of consecutive items in a list](https://stackoverflow.com/questions/21303224/iterate-over-all-pairs-of-consecutive-items-in-a-list) – FazeL Sep 02 '21 at 06:43

3 Answers3

3

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

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
1

As explained here you can use:

from itertools import tee

def nwise(iterable, n=2):                                                      
    iters = tee(iterable, n)                                                     
    for i, it in enumerate(iters):                                               
        next(islice(it, i, i), None)                                               
    return izip(*iters)   
martineau
  • 119,623
  • 25
  • 170
  • 301
FazeL
  • 916
  • 2
  • 13
  • 30
0

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.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264