David Eyk David Eyk - 2 years ago 114
Python Question

How do I merge two python iterators?

I have two iterators, a

and an
object (i.e. an infinite value generator). I would like to merge these two into a resulting iterator that will alternate yield values between the two:

>>> import itertools
>>> c = itertools.count(1)
>>> items = ['foo', 'bar']
>>> merged = imerge(items, c) # the mythical "imerge"
>>> merged.next()
>>> merged.next()
>>> merged.next()
>>> merged.next()
>>> merged.next()
Traceback (most recent call last):

What is the simplest, most concise way to do this?

Answer Source

A generator will solve your problem nicely.

def imerge(a, b):
    for i, j in itertools.izip(a,b):
        yield i
        yield j
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download