Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join two generators in Python?

People also ask

Can you zip generators in Python?

Now you can: Use the zip() function in both Python 3 and Python 2. Loop over multiple iterables and perform different actions on their items in parallel. Create and update dictionaries on the fly by zipping two input iterables together.

Can we call generator multiple times in Python?

Unless your generator is infinite, you can iterate through it one time only. Once all values have been evaluated, iteration will stop and the for loop will exit. If you used next() , then instead you'll get an explicit StopIteration exception.

How do you make a generator in Python?

It is fairly simple to create a generator in Python. It is as easy as defining a normal function, but with a yield statement instead of a return statement. If a function contains at least one yield statement (it may contain other yield or return statements), it becomes a generator function.

What is a generator expression Python?

A generator expression is an expression that returns a generator object. Basically, a generator function is a function that contains a yield statement and returns a generator object.


itertools.chain() should do it.

It takes a list of iterables and yields from each one by one

def chain(*iterables):
    for it in iterables:
        for element in it:
            yield element

Usage example:

from itertools import chain
generator = chain('ABC', 'DEF')

for item in generator:
    print(item)

Output:

A
B
C
D
E
F

A example of code:

from itertools import chain

def generator1():
    for item in 'abcdef':
        yield item

def generator2():
    for item in '123456':
        yield item

generator3 = chain(generator1(), generator2())
for item in generator3:
    print item

In Python (3.5 or greater) you can do:

def concat(a, b):
    yield from a
    yield from b

Simple example:

from itertools import chain
x = iter([1,2,3])      #Create Generator Object (listiterator)
y = iter([3,4,5])      #another one
result = chain(x, y)   #Chained x and y

With itertools.chain.from_iterable you can do things like:

def genny(start):
  for x in range(start, start+3):
    yield x

y = [1, 2]
ab = [o for o in itertools.chain.from_iterable(genny(x) for x in y)]
print(ab)

Here it is using a generator expression with nested fors:

a = range(3)
b = range(5)
ab = (i for it in (a, b) for i in it)
assert list(ab) == [0, 1, 2, 0, 1, 2, 3, 4]