# [Tutor] What does yield do?

Alan Gauld alan.gauld at yahoo.co.uk
Tue Feb 28 06:31:50 EST 2023

```On 28/02/2023 09:18, Albert Cornelius wrote:
> 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

I don't think Java has any similar feature so Java
probably won't help here.

yield is like a "return and pause" statement.
It returns the current value but does not terminate
the function, instead the function goes to sleep
until next called. When it is called the next time
it picks up from the statement after the yield.

def simpleYield():
yield 1   # result of first use
yield 2   # result of 2nd use
yield 3   # last use.

for n in range(3):
print(simpleYield())

Except that doesn't work because the function is
not a regular function. By using yield it becomes
a generator (personally, I wish they'd defined a
new word to make that explicit - defgen or somesuch...)

So to use simpleYield we have to "instantiate" it:

gen = simpleYield()
and now we can use the generator:

for n in gen: print(n)  #-> 1,2,3

Now that example is pretty pointless. But imagine
you want to return an infinitely long list, the list
of all odd numbers starting at 1. To do that without
a generator(ie yield) would require either a global
variable (ugly) or defining a class - quite a lot
of work.

Defining a generator is simpler:

def odds():
n = 1
while True:
yield n
n += 2

allOdds = odds()

for n in allOdds:
if n >10: break  # avoid going to infinity and beyond!
print(n)

That's about as simple as I can make it for a
(pretty smart!) 5 year old. :-)
If you need more, ask away.

You might find the original proposal (PEP255) useful if

https://peps.python.org/pep-0255

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos

```