How to turn Python list to consecutive tuples including edge items?

Viewed 995

For a Python list:

l = list('ABCDEFG')

How can it be turned into a list of consecutive N-tuples, with the edge cases not thrown out? Here is an example for N=3:

A
A B
A B C
B C D
C D E
D E F
E F G
F G
G

I can get close with

for first, second, third in zip(l,l[1:],l[2:]):
    print(first, second, third)

But this does not include the edge cases and can not be extended easily to other N. I can patch it up with a C-looking for loop, checking for array bound validity, but it quickly grows to be a web of nested if statements and I'm looking for a more Pythonic solution.

4 Answers
Related