using deque:
from itertools import islice from collections import deque def grps(l, gps, stp): d = deque(l) for i in range(0, len(l), stp): yield list(islice(d, gps)) d.rotate(-stp)
output:
In [7]: l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] In [8]: list(grps(l, 3, 2)) Out[8]: [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10, 1]] In [9]: list(grps(l, 4, 2)) Out[9]: [[1, 2, 3, 4], [3, 4, 5, 6], [5, 6, 7, 8], [7, 8, 9, 10], [9, 10, 1, 2]]
You can also join to get the islice object and decide what you want to do with it outside:
def grps(l, gps, stp): d = deque(l) for i in range(0, len(l), stp): yield islice(d, gps) d.rotate(-stp)
Output:
In [11]: for gp in grps(l, 3,2): ....: print(" ".join(map(str,gp))) ....: 1 2 3 3 4 5 5 6 7 7 8 9 9 10 1
Or just with a module:
def grps(l, gps, stp): ln = len(l) for i in range(0, len(l), stp): yield (l[j % ln] for j in range(i, i + gps)) for gp in grps(l, 4, 2): print(" ".join(map(str, gp)))