Python Forum
Yield statement question - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Yield statement question (/thread-29931.html)



Yield statement question - DPaul - Sep-26-2020

I have been reading up on the "yield" instead of "return" statement.
Arguably, I understand what it does.

On most sites however, they give the generic(?) example of how to
print the squares of the numbers from 1 to 10 using a def function with a while loop etc..
They need 10 lines of code for that yield example (even taking out the comment lines)
Anybody can print those squares in 2, let alone 1 line of code.

Question: could somebody describe - in words only - a situation where using "yield"
provides a huge benefit?

thx,
Paul


RE: Yield statement question - Gribouillis - Sep-26-2020

"Yield" is useful in separating concerns. It separates the code that creates a collection of similar entities from the code that uses this collection. You can decide to print these items or store them in a container or whatever, but the function that generates the items doesn't need to know what you are going to do with them. Its sole responsibility is the production of these items.


RE: Yield statement question - ndc85430 - Sep-26-2020

One use case is for generators that allow you to create potentially infinite sequences. Obviously, you can't store such things in memory, so this technique allows you to compute the next value on demand as you iterate. The idea is called "lazy evaluation" in general.


RE: Yield statement question - DPaul - Sep-26-2020

OK, useful info thanks.
Maybe we could somehow experiment this in seeding a "Conway game of life"

thx,
Paul


RE: Yield statement question - Gribouillis - Sep-26-2020

You know that John Conway died this spring of Covid 19?


RE: Yield statement question - perfringo - Sep-26-2020

Simple answer: stacked generators result in processing pipelines

But are you ready to bend your mind? If yes then David Beazley - Generators the Final Frontier is waiting you.


RE: Yield statement question - DPaul - Sep-26-2020

(Sep-26-2020, 03:00 PM)Gribouillis Wrote: You know that John Conway died this spring of Covid 19?

Yes I do.
He wrote the book !

As for " David Beazley - Generators the Final Frontier" : i'll need to look into that.
Sounds exciting Huh

Paul