1

So I have the following generator function:

def gen(n=5):
    for i in range(n):
        n = yield n

for i in gen(3):
    print(i)

The result:

3
None
None

I understand the first result of yield is 3. Because I assigned 3 to function argument n. But where are the None in the second and third yield coming from? Is it because in the for-loop, yield n returns None and this None is assigned to n in this line: n = yield n?

4
  • 2
    What have you gathered from the generator and yield statement documentation? Commented Nov 25, 2022 at 12:27
  • 2
    Yes, you have provided your explanation. Commented Nov 25, 2022 at 12:30
  • you should call gen() from INSIDE the loop Commented Nov 25, 2022 at 12:48
  • @Roland And why would you want to do that? Commented Nov 25, 2022 at 13:01

2 Answers 2

4

This is explained in the documentation of yield expressions, especially this part:

The value of the yield expression after resuming depends on the method which resumed the execution. If next() is used (typically via either a for or the next() builtin) then the result is None. Otherwise, if send() is used, then the result will be the value passed in to that method.

As you use a for loop, n just gets None as a value when resuming after the first yield. So, from now on, n is None, and this is what will be yielded the last two times.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I understand now. It's interesting send() is designed to change the result value of the yield expression. I thought send() was to insert a new value in the sequence being yielded.
2

It seems to me that you answered your own question:

because in the for-loop, yield n returns None and None is assigned to n in this line: n = yield n

You can read more at this answer.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.