Skip to content

Instantly share code, notes, and snippets.

@addam
Created September 22, 2016 20:27
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 addam/b46446c2867e98fd6b2ddbdedbe8961c to your computer and use it in GitHub Desktop.
Save addam/b46446c2867e98fd6b2ddbdedbe8961c to your computer and use it in GitHub Desktop.
iterate over consecutive pairs
def pairs(seq, cyclic=True):
it = iter(seq)
first = prev = next(it)
for here in it:
yield prev, here
prev = here
if cyclic:
yield here, first
# I use this snippet in almost every script
# It is really simple but still I would prefer to import it from itertools if it was there...
# If you know of a more elegant way to do this, please give me a note
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment