Python Forum

Full Version: iterating a span of a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i'm looking for something that can do like this span() function can:
a = ['foo','bar','boo','far','baz']
for b in span(a,3):
    print(*b)
a = [1,2,3,4,5,6,7,8,9]
for b in span(a,4):
    print(*b)
Output:
foo bar boo bar boo far boo far baz 1 2 3 4 2 3 4 5 3 4 5 6 4 5 6 7 5 6 7 8 6 7 8 9
this shouldn't be hard to code, but if zip() exists, maybe something like this span() exists. if it would return an iterator, that would be fine.
It looks like more_itertools.windowed()
implementing it was next to trivial. a slice in a comprehension.
def span(s,n):
    return iter([s[x:x+n]for x in range(len(s)-n+1)])
import itertools
from functools import partial


def window(sequence, window_size, uncomplete=True, fillvalue=None):
    if uncomplete:
        izip = partial(itertools.zip_longest, fillvalue=fillvalue)
    else:
        izip = zip
    yield from izip(*[iter(sequence)] * window_size)
l = list(range(10))
for chunk in window(l, 3):
    print(chunk)
Output:
(0, 1, 2) (3, 4, 5) (6, 7, 8) (9, None, None)
If you use uncomplete=False, the zip function will be used.
The zip function stops iterating, if there are not enough values, to fill the window.

l = list(range(10))
for chunk in window(l, 3, uncomplete=False):
    print(chunk)
Output:
(0, 1, 2) (3, 4, 5) (6, 7, 8)
The more_itertools implementation uses a deque, but it works with any iterable, not only iterables with random access.

@DeaD_EyE I think your function does something different.
yes, DeaD_EyE's result is different.