+3

# Generators (yield). Send() method.

Can somebody please explain me how does send() method work in generators? https://code.sololearn.com/c28YFxTnaak2/?ref=app

2/16/2020 12:06:10 PM

Mikhail

5 Answers

New Answer

+4

Send makes the next yield Docu says send(None) is equal to yield

+4

I commented in code. that is indeed very interesting

+3

After reading the docs and thinking a while, I come to the following result: a.send(100) does not send x but the yield expression yield x. Python must do so, otherwise it had problems handling send() for a generator gen(x,y): while True: yield(3x +4y) What would you send in this case if send has exactly 1 argument. As a model u can regard yield x as a variable that is created with first yield and can be manipulated with send()

+2

But if so, why in my second example (gen1) where generator uses double “yield” statement, b.send(100) prints out 100?

+2

So, send() does the same as next()? P.S. If you run my code now, you will see a very interesting thing in the second example with double “yield”! It looks like these two “yields” work one after another: with first “next()” it prints out the first element of generator (so I guess the inner “yield x” does this), but with second “next()” it prints out “None” (as if outer “yield” is doing this). And if I write “send(value)” instead of the second “next()”, it prints out the “value” of “send”!