Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does generator yield value after loop

I’ve been learning how send method and yield assignment work in generator and met a problem:

def gen():
    for i in range(5):
        x = yield i
        print(x)
s = gen()
print(next(s))
print(s.send(15))

output:

0 #after print(next(s))
15
1

so it prints 15 and 1 after print(s.send(15)). It broke my understanding of yield, because I don’t understand why it yields 1 after printing x. I’m wondering if someone knows the answer.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When you call s.send(15) the generator resumes running. The value of yield is the argument to s.send(), so it does x = 15 and the generator prints that. Then the for loop repeats with i = 1, and it does yield i.

The value of s.send() is the next value that’s yielded, so print(s.send(15)) prints that 1.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading