0

I want to access overlapping pairs of adjacent values in a generator.

If it was a list, I could use

a = [5, 7, 11, 4, 5]
for v, w in zip(a[:-1], a[1:]):
    print [v, w]

Which is from this question.

But when I try to do the same with a generator, I get the error

TypeError: 'generator' object is not subscriptable

Is there a way to do this for generators?

Community
  • 1
  • 1
Vermillion
  • 1,238
  • 1
  • 14
  • 29

1 Answers1

5

I would create a generator function to do this:

def adjacent_pairs(it):
    it = iter(it)
    a, b = next(it), next(it)
    while True:
        yield a, b
        a, b = b, next(it)

Example usage:

def gen():
    yield 5
    yield 7
    yield 11
    yield 4
    yield 5
for v, w in adjacent_pairs(gen()):
    print [v, w]
Robᵩ
  • 163,533
  • 20
  • 239
  • 308