So I understand how generators and coroutines work. Broadly speaking, generators produce data and coroutines consume data. Now, what I am trying to do is combine both these features.
I have defined a coroutine that receives a list as an input and then tries to **yield** items from the list one at a time, like a generator would do.
Here is my code -
def coroutine():
print('Starting coroutine')
value = (yield)
for i in value:
yield i
c=coroutine()
c.__next__()
c.send([1,2,3,4,5])
for val in c:
print(val)
The problem is, the first list item is being lost. The value 1 is not being returned from the coroutine.
Based on my understanding, the flow should have been as follows.
c=coroutine()----> Declares thecoroutinewithout starting it.c.__next__()----> This starts thecoroutineand it advances to the line -value = (yield)and stops there.c.send([1,2,3,4,5])----> This passes the newlistto the waiting coroutine i.evalue = (yield). The coroutine now proceeds to the nextyieldstatement inside the for loop.- The for loop in the main program is supposed to receive each items of the list that it initially passed. But this does not happen.
Can you please explain why ? The reason I am trying to do this is to generate a pipeline. Each component will receive items, modify it and then yield it to the next coroutine in the pipeline.
Please help.
EDIT --------------------
The output is as follows -
Starting coroutine
2
3
4
5