Why does generator yield value after loop

Question:

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.

Asked By: Ice Cube

||

Answers:

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.

Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.