Akansha Yadav shows how Python's yield keyword creates memory-efficient generators. She builds a cube generator that produces 1, 8, 27, 64, 125 for an input of 5, replacing return with yield to iterate over values instead of storing them all at once.
Chapters
In today's video, we will discuss about the yield keyword in Python. Yield keyword is basically used to create a generator function and a type of a function that is memory efficient and can be used like an object. So let's create it. I am going to create a cube generator. For this, I am using function loop and then adding a yield operator instead of a return statement. So this will be a generator function this time. Then I am using an input. Now I am creating a generator object. It means I am calling my function and passing a value in it. And then iterating over a generator to print the cube. So I am using the cubes, the object that I have created, inside the loop. So here I am iterating it. That is what we call a generator function. So let's test our file and see what is going to be the output, that whether we are getting a cube or not. So let me run it, and here we got our output. I am entering an input number, let's suppose I want 5. So for 1, it's 1. For 2, the cube of 2 is 8. Then same with 27, 64, and 125. If you like the video, don't forget to subscribe the channel.