Jayde
Jayde

Reputation: 57

How can I create a generator which combines two generators' data, element-wise?

I have a generator which iterates over strings, eg ['apple', 'banana', orange']. I have an additional generator which iterates over a different set of strings, eg ['car', 'truck', 'bike']

I'd like to create a generator, that when iterated over, returns the following: 'applecar', 'bananatruck', 'orangebike'.

Is there a way to do this?

Upvotes: 0

Views: 126

Answers (1)

Zachary Vance
Zachary Vance

Reputation: 872

Yes, but make sure to think about what you want to happen if the two are different lengths.

def generator(a, b):
    for a_element, b_element in zip(a,b):
        yield a_element + b_element

or more compactly:

new_gen = ( a_element + b_element for a_element,b_element in zip(a,b) )

Upvotes: 1

Related Questions