Ice Cube
Ice Cube

Reputation: 53

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.

Upvotes: 1

Views: 126

Answers (1)

Barmar
Barmar

Reputation: 780984

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.

Upvotes: 7

Related Questions