'Sketch for a C code implementation of pairwise()' null = object() class Pairwise: __slots__ = ('it', 'old') def __init__(self, iterable): self.it = iter(iterable) self.old = null def __iter__(self): return self def __next__(self): if self.it is null: raise StopIteration if self.old is null: self.old = next(self.it, null) if self.old is null: self.it = null raise StopIteration old = self.old new = next(self.it, null) if new is null: self.it = null self.old = null raise StopIteration result = old, new self.old = new return result if __name__ == '__main__': 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) assert list(pairwise('')) == list(Pairwise('')) assert list(pairwise('a')) == list(Pairwise('a')) assert list(pairwise('ab')) == list(Pairwise('ab')) assert list(pairwise('abc')) == list(Pairwise('abc')) assert list(pairwise('abcd')) == list(Pairwise('abcd')) assert list(pairwise('abcde')) == list(Pairwise('abcde')) for pair in Pairwise('abcdefgh'): print(pair)