def window(iterable, n=2, cast=tuple):
    """ This function passes a running window along the length of the given
        iterable.  By default, the return value is a tuple, but the cast
        parameter can be used to change the final result.
    """
    it = iter(iterable)
    win = deque((next(it) for _ in repeat(None, n)), maxlen=n)
    if len(win) < n:
        raise ValueError('Window size was greater than iterable length')
    yield cast(win)
    append = win.append
    for e in it:
        append(e)
        yield cast(win)
This function passes a running window along the length of the given
        iterable.  By default, the return value is a tuple, but the cast
        parameter can be used to change the final result.