Skip to content

Instantly share code, notes, and snippets.

@bbayles
Created June 19, 2019 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbayles/62b3c31f5410f3b5311fce171b789e4c to your computer and use it in GitHub Desktop.
Save bbayles/62b3c31f5410f3b5311fce171b789e4c to your computer and use it in GitHub Desktop.
from itertools import chain, islice, tee
from more_itertools import consume
_marker = object()
class iterchunked:
def __init__(self, iterable, n):
self._source = iter(iterable)
self._n = n
self._init = False
def __iter__(self):
return self
def __next__(self):
if self._init:
consume(self._source, self._n)
else:
self._init = True
item = next(self._source, _marker)
if item is _marker:
raise StopIteration
else:
self._source = chain([item], self._source)
self._source, it = tee(self._source, 2)
return islice(it, self._n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment