Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Created March 19, 2014 04:14
Show Gist options
  • Save carymrobbins/9635336 to your computer and use it in GitHub Desktop.
Save carymrobbins/9635336 to your computer and use it in GitHub Desktop.
def groups_of(n, xs, **kwargs):
"""
Returns n elements from xs until empty.
Optional 'pad' keyword argument will pad a value to the resulting iterator
to meet
>>> for x in groups_of(2, [1, 2, 3, 4, 5]):
... print x
[1, 2]
[3, 4]
[5]
>>> for x in groups_of(3, [1, 2, 3, 4, 5], pad=None):
... print x
[1, 2, 3]
[4, 5, None]
"""
if 'pad' in kwargs:
pad, use_padding = kwargs.pop('pad'), True
else:
pad, use_padding = None, False
xs = iter(xs)
while True:
result = []
for i in range(n):
try:
result.append(xs.next())
except StopIteration:
if result:
if use_padding:
result += [pad] * (n - i)
yield result
return
yield result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment