Search code examples
pythongeneratorpython-itertools

Reverse the `pairwise` generator


I've got a generator similar to the itertools' pairwise recipe, which yields (s0,s1), (s1,s2), (s2, s3).... I want to create another generator from it that would yield the original sequence s0, s1, s2, s3,....

from itertools import *

def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

a = [1,2,3,4]

for item in unpair(pairwise(a)):
   print item # should print 1,2,3,4

How to write unpair as a generator, without resorting to lists?


Solution

  • Maybe:

    def unpair(iterable):
        p = iter(iterable)
        return chain(next(p, []), (x[1] for x in p))