Created
September 22, 2016 20:27
-
-
Save addam/b46446c2867e98fd6b2ddbdedbe8961c to your computer and use it in GitHub Desktop.
iterate over consecutive pairs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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