Skip to content

Instantly share code, notes, and snippets.

@oinopion
Created October 9, 2013 09:11
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 oinopion/6898479 to your computer and use it in GitHub Desktop.
Save oinopion/6898479 to your computer and use it in GitHub Desktop.
A iterator that converts single sequence into iterable of lists length n.
def in_batches(sequence, n=2):
"""
>>> list(in_batches([1, 2, 3, 4, 5], n=2))
[[1, 2], [3, 4], [5, None]]
"""
iterable = iter(sequence)
try:
while True:
values = [None] * n
for i in xrange(n):
values[i] = iterable.next()
yield values
except StopIteration:
if values[0] is not None:
yield values
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment