Using a generator expression:
from itertools import count try: _range = xrange except NameError:
Demo:
>>> list(incremental_window([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])) [[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]] >>> list(incremental_window([1, 2, 3, 4])) [[1], [2, 3]] >>> list(incremental_window([1, 2, 3, 4, 5, 6])) [[1], [2, 3], [4, 5, 6]]
This is a generator that will work with any iterable, including endless iterations:
>>> from itertools import count >>> for window in incremental_window(count()): ... print window ... if 25 in window: ... break ... [0] [1, 2] [3, 4, 5] [6, 7, 8, 9] [10, 11, 12, 13, 14] [15, 16, 17, 18, 19, 20] [21, 22, 23, 24, 25, 26, 27]
You can do this with one liner with a little trick to "embed" the iter() call in your list object:
list([next(it) for _ in _range(s)] for it in (iter(my_list),) for s in count(1))