Skip to content

Instantly share code, notes, and snippets.

@pilcrow
Created January 16, 2017 13:43
Show Gist options
  • Save pilcrow/8b6af7e35f5d19de7702d77446461b02 to your computer and use it in GitHub Desktop.
Save pilcrow/8b6af7e35f5d19de7702d77446461b02 to your computer and use it in GitHub Desktop.
Python iterate N items at a time
import itertools
def natatime(n, iterable, fillvalue = None):
"""Returns an iterator yielding `n` elements at a time.
:param n: the number of elements to return at each iteration
:param iterable: the iterable over which to iterate
:param fillvalue: the value to use for missing elements
:Example:
>>> for (a,b,c) in natatime(3, [1,2,3,4,5], fillvalue = "?"):
... print a, b, c
...
1 2 3
4 5 ?
"""
stepped_slices = ( itertools.islice(iterable, i, None, n) for i in xrange(n) )
return itertools.izip_longest(*stepped_slices, fillvalue = fillvalue)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment