Skip to content

Instantly share code, notes, and snippets.

@Mause
Created July 15, 2015 11:37
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 Mause/8f09062debae85a480d5 to your computer and use it in GitHub Desktop.
Save Mause/8f09062debae85a480d5 to your computer and use it in GitHub Desktop.
Efficient, lazy, iterator, python pairing
from itertools import chain, tee
def pairs(iterator):
"""
Returns the items in the iterator pairwise, like so;
>>> list(pairs([0, 1, 2]))
[(0, 1), (1, 2)]
"""
first, second = tee(iterator)
ret = zip(chain([None], second), first)
# this is a generator so that execution doesn't begin until the user
# starts consuming us, and so that we then don't start consuming our
# iterator until they ask us to
next(ret) # kill the first half-empty pair
yield from ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment