You got some clever answers here, but I would suggest that the most obvious way to do this is simply using the built-in indexing of slices. For instance:
def gen_k_slices(seq, k): for i in range(len(seq) - k + 1): yield seq[i:i+k]
Here is a small test driver:
TEST = [1, 2, 3, 4, 5, 6] for k in range(8): print("k={} -> {}".format(k, list(gen_k_slices(TEST, k))))
and its conclusion:
k=0 -> [[], [], [], [], [], [], []] k=1 -> [[1], [2], [3], [4], [5], [6]] k=2 -> [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] k=3 -> [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6]] k=4 -> [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]] k=5 -> [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6]] k=6 -> [[1, 2, 3, 4, 5, 6]] k=7 -> []
I also don't like the result for k = 0 :-)