[Tutor] What does yield do?

ThreeBlindQuarks threesomequarks at proton.me
Tue Feb 28 13:19:52 EST 2023


Albert,

Don't yield to the temptation to just give up and never return!

It is actually quite simple once you realize that a regular function is called and does things and a "return" statement optionally sends back a result. The details loosely are the function is placed on a stack and then goes away leaving the result on the stack and that is grabbed and goes away and you keep doing what comes next. Functions often are short-lived.

What is new in generators of several kinds is that they simply do not go away. They stick around by NOT using return. Instead, when they have calculated the next thing to return, with more perhaps to come later, they "yield" the result and are suspended until needed again. All internal state such as variables remain alive and well.

The function that called the generator gets back a result and may later, it or another function, ask for the next iteration and the generator wakes up and calculates to the next "yield" and that is sent back.

Some generators never end and some do some kind of return when finally done or send back some signal.

So yield is just a cousin of return.

There is always more such as YIELD FROM.

Just FYI, your example is not quite the best as it calls range() to generate all the values then returns just one at a time. But range itself is a generator now so it does not need to calculate all of them at once.


Sent with Proton Mail secure email.

------- Original Message -------
On Tuesday, February 28th, 2023 at 4:18 AM, Albert Cornelius <albert1.cornelius at gmail.com> wrote:


> I've seen some examples on yield like this:
> 
> > > > def create_generator():... mylist = range(3)... for i in mylist:... yield i*i
> 
> ...>>> mygenerator = create_generator() # create a generator>>>
> 
> print(mygenerator) # mygenerator is an object!
> <generator object create_generator at 0xb7555c34>>>> for i in
> 
> mygenerator:... print(i)014
> 
> 
> and I've read some amout of text about it. But I still don't really
> grasp the idea of yield. I'm coming from the Java world and am in my
> 2nd semester, so please be kind. Can someone please provide an ELI5
> (Explain Like I'm 5) explanation of what yield does?
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


More information about the Tutor mailing list