Return vs yield in Python with example

Hey coder! at last here comes the article where we are going to learn the differences between return and yield keywords in Python, with examples.

return keyword in Python

In Python, we are having a keyword called “return”, which is used inside the function definition to bunce any type of value or object…

The return statement is an important part of the function which allows us to use the same function in multiple regions of our code.

Example code:

def cube(num):           # function definition  
    x = num*num*num
    return num

print(num(3))            # function call

In the above example code, we are creating a function and returning the cube of a number.
We can call the function whenever it is necessary for our code.

So that we can call the function and get the value whenever we want.

Output

27

yield keyword in Python

In Python, we can return objects and values not only with the return keyword but also with the yield keyword.

The yield keyword is equally important as the return keyword

And the main difference between the return statement and yield statement is:

  • When we use the yield keyword, the local variable states will not get affected.

Basically, the yield returns the generator.

Example Code:

def function(l):
    yield l
l=[1,2,3,4,5,76]
print(function(l))

In the above code, the function will return the generator object only, but not the given list.

Output

<generator object function at 0x7f8b8fe86ac0>

Finally, we have come to an end of this article.

And this is all about the return and yield statements in Python.

I hope you have learned something from this.

Keep Learning!

You can go through the below links on your interest:

Leave a Reply

Your email address will not be published.