Take the 2-minute tour ×

I have a list lg of generators, lg = [g1, g2, ..., gn]. Those generators are merged into one generator with izip, G = izip(*lg). One of the generators in lg (say g1) is usually constructed itself through izip, so its generated result appears as a tuple when iterating over G. However, I need the tuple unpacked, i.e when iterating over G, G should generate a tuple with no nested tuples. Is it possible to unpack g1 when constructing G?

Edit: An Example (shortend version from @jsbueno):

from itertools import izip

g1 = izip(xrange(1,3), xrange(3,5))
g2 = xrange(10, 13)
g3 = xrange(20, 23)

lg = [g1, g2, g3]

for i in izip(*lg):
    print i


((1, 3), 10, 20)
((2, 4), 11, 21)

but I need

(1, 3, 10, 20)
(2, 4, 11, 21)
share|improve this question

1 Answer 1

up vote 1 down vote accepted

Since for what you want the "izip" needs information about the iterators inside the inner izips - and izip is opaque in relation to that (that is, you can't fetch the arguments to an izip given an izip object) - th way to go is to reimplement the functionality of izip, but in a way that is aware of it - and if the result yielded by one of the passed iterators is a tuple, to concatenate it to the results, instead of adding it as a single item:

class FlatIzip(object):
    def __init__(self, *args):
        self.generators = args
    def __iter__(self):
        iters = [iter(x) for x in self.generators]
        while True:
            result = []
            for iterator in iters:
                element = iterator.next()
                if isinstance(element, tuple):
                    result += list(element)
            yield tuple(result)


from itertools import izip

g1 = xrange(10)
g2 = xrange(10,20)
g3 = xrange(20, 30)
g4 = izip(xrange(40,50), xrange(50,60))

lg = [g1, g2, g3, g4]

for x in FlatIzip(*lg):
    print x
share|improve this answer

Your Answer


