Split list into separate but overlapping chunks

Simply use Python’s built-in list comprehension with list-slicing to do this:

>>> A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> size = 3
>>> step = 2
>>> A = [A[i : i + size] for i in range(0, len(A), step)]

This gives you what you’re looking for:

>>> A
[[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]]

But you’ll have to write a couple of lines to make sure that your code doesn’t break for unprecedented values of size/step.

Leave a Comment