1

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
  • 95,415
  • 23
  • 151
  • 231
  • 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

4 Answers4

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
  • 13,387
  • 4
  • 15
  • 42
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
  • 112,593
  • 23
  • 157
  • 280
FazeL
  • 876
  • 2
  • 15
  • 27
0

try this:

list(map(list , (listt[i:i+n] for i in range(len(listt)-(n-1)))))

output:

# n = 2
[[2, 0], [0, 5], [5, 4], [4, 2]]
# n = 3
[[2, 0, 5], [0, 5, 4], [5, 4, 2]]
# n = 4
[[2, 0, 5, 4], [0, 5, 4, 2]]
I'mahdi
  • 11,310
  • 3
  • 17
  • 23
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
  • 95,415
  • 23
  • 151
  • 231