Difference - Return vs Yield

Hi. What is the difference between the two keywords?

def fun(n):
    for i in range(n):
        return i
def fun(n):
    for i in range(n):
        yield i

Also, what does the exception mean? ‘int’ obj not iterable
err

Thanks.

It is only possible to return from a function once per time it is called. The loop here will not be useful. The function will only return 0 (as long as the range is not empty and there is no other problem).

If you need to “collect” multiple results from a loop, and get them back from the function there are many ways to do that:

One of those ways uses your other code example, so let’s look at it.

When the code for a function has yield in it, like this, that turns the entire function into a generator function. This has special rules and does not work like an ordinary function.

When you call a generator function, you get back a generator object. This works a little bit like a file: you can get the values from it “on demand”, so you can write a loop over the “contents” without needing to store it all in memory.

A for loop only needs any kind of iterator:

It can use a list, or a range object, or a generator, or many other kinds of things.

This version of the code will allow us to write the for loop with the result:

for v in fun(5):
    print(v)

Calling fun(5) created the generator, and then the loop prints the values that are “found” in the generator, as it’s doing the work.

Exactly as it says. “iterable” is explained in the link above. When you used the first function, it gave back only the integer 0. This is not iterable: it doesn’t represent more values that we can use for a loop. for v in 0: doesn’t make any sense: 0 isn’t something that can have other things in it. That’s why this error is a TypeError: integers are the wrong type of thing to use here.

You may also find these useful:

Once you hit a return statement, the function stops right there (there are some exceptions, pun intended, but otherwise that’s the end of the function). But a yield in a generator can be resumed from. It’s a sort of “continuable return”, where you give a value back to your caller, but can come right back in where you left off.

1 Like