Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zhoudaxia233/6bc25cafc053a22dd057c6d9ecead0f3 to your computer and use it in GitHub Desktop.
Save zhoudaxia233/6bc25cafc053a22dd057c6d9ecead0f3 to your computer and use it in GitHub Desktop.
Python: Iterating over every two elements in a list

Type 1:

from itertools import tee
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

Type 2:

def pairwise(iterable):
    "s -> (s0, s1), (s2, s3), (s4, s5), ..."
    a = iter(iterable)
    return zip(a, a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment