Skip to content

Instantly share code, notes, and snippets.

@tiwijo
Created December 7, 2011 19:51
Show Gist options
  • Save tiwijo/1444329 to your computer and use it in GitHub Desktop.
Save tiwijo/1444329 to your computer and use it in GitHub Desktop.
Iterate over N adjacent elements of a list
from itertools import tee, izip
def inwise(iterable, n=2):
'''Return an iterator over iterable where n adjacent items are returned at
a time.
@param n : int
the number of adjacent items to return'''
iters = tee(iterable, n=n)
for i in xrange(1, n):
for j in xrange(i, n):
iters[j].next()
return izip(*iters)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment